如何解决使用大量自定义组件创建复杂表单的问题?
How to tackle creating complex form with lots of custom components?
假设我从 angular2 应用生成的 html 如下所示:
<app>
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
<panel-component>
<mid-component>
<inner-component-with-inputs>
<input/>
<inner-component-with-inputs>
<mid-component>
</panel-component>
<panel-component>
<mid-component>
<inner-component-with-inputs>
<input/>
<inner-component-with-inputs>
<mid-component>
</panel-component>
<!-- many many many fields -->
<button type="submit">Submit</button>
</form>
</app>
如何设置外部 <form>
以便在提交时验证所有内部输入?我是否必须通过 myForm
通过 @Input()
从 panel-component
一直向下传递到 inner-component-with-inputs
?还是有别的办法?
在我的应用程序中,我有一个非常大的表单,包含多个面板、子面板、选项卡、模态框等,我需要能够在提交时立即验证它。
互联网上的所有教程和资源都只讨论跨越一个 component/template 的表格。
当涉及 parent/child 关系时,您将在整个 Angular 源代码中看到的一个常见模式是 parent 类型将自身添加为自身的提供者。这样做是允许 child 组件注入 parent。由于 hierarchical DI,在组件树 下 的整个过程中,只有一个 parent 组件的实例。下面是一个可能看起来像的例子
export abstract class FormControlContainer {
abstract addControl(name: string, control: FormControl): void;
abstract removeControl(name: string): void;
}
export const formGroupContainerProvider: any = {
provide: FormControlContainer,
useExisting: forwardRef(() => NestedFormComponentsComponent)
};
@Component({
selector: 'nested-form-components',
template: `
...
`,
directives: [REACTIVE_FORM_DIRECTIVES, ChildComponent],
providers: [formGroupContainerProvider]
})
export class ParentComponent implements FormControlContainer {
form: FormGroup = new FormGroup({});
addControl(name: string, control: FormControl) {
this.form.addControl(name, control);
}
removeControl(name: string) {
this.form.removeControl(name);
}
}
一些注意事项:
我们使用 interface/abstract parent (FormControlContainer
) 有几个原因
- 它将
ParentComponent
与 ChildComponent
分离。 child 不需要了解特定 ParentComponent
的任何信息。它所知道的只是 FormControlContainer
和它所拥有的合同。
- 我们仅通过接口契约在
ParentComponent
上公开方法。
我们只广告 ParentComponent
作为FormControlContainer
,所以后者是我们要注入的。
我们以 formControlContainerProvider
的形式创建一个提供者,然后将该提供者添加到 ParentComponent
。由于分层 DI,现在所有 children 都可以访问 parent.
如果你不熟悉forwardRef
,this is a great article
现在在child(ren)中你可以做到
@Component({
selector: 'child-component',
template: `
...
`,
directives: [REACTIVE_FORM_DIRECTIVES]
})
export class ChildComponent implements OnDestroy {
firstName: FormControl;
lastName: FormControl;
constructor(private _parent: FormControlContainer) {
this.firstName = new FormControl('', Validators.required);
this.lastName = new FormControl('', Validators.required);
this._parent.addControl('firstName', this.firstName);
this._parent.addControl('lastName', this.lastName);
}
ngOnDestroy() {
this._parent.removeControl('firstName');
this._parent.removeControl('lastName');
}
}
IMO,这是一个比通过 @Input
传递 FormGroup
更好的设计。如前所述,这是整个 Angular 来源的通用设计,因此我认为可以肯定地说这是一个可接受的模式。
如果你想让 child 组件更可重用,你可以使构造函数参数 @Optional()
.
下面是我用来测试上述例子的完整源代码
import {
Component, OnInit, ViewChildren, QueryList, OnDestroy, forwardRef, Injector
} from '@angular/core';
import {
FormControl,
FormGroup,
ControlContainer,
Validators,
FormGroupDirective,
REACTIVE_FORM_DIRECTIVES
} from '@angular/forms';
export abstract class FormControlContainer {
abstract addControl(name: string, control: FormControl): void;
abstract removeControl(name: string): void;
}
export const formGroupContainerProvider: any = {
provide: FormControlContainer,
useExisting: forwardRef(() => NestedFormComponentsComponent)
};
@Component({
selector: 'nested-form-components',
template: `
<form [formGroup]="form">
<child-component></child-component>
<div>
<button type="button" (click)="onSubmit()">Submit</button>
</div>
</form>
`,
directives: [REACTIVE_FORM_DIRECTIVES, forwardRef(() => ChildComponent)],
providers: [formGroupContainerProvider]
})
export class NestedFormComponentsComponent implements FormControlContainer {
form = new FormGroup({});
onSubmit(e) {
if (!this.form.valid) {
console.log('form is INVALID!')
if (this.form.hasError('required', ['firstName'])) {
console.log('First name is required.');
}
if (this.form.hasError('required', ['lastName'])) {
console.log('Last name is required.');
}
} else {
console.log('form is VALID!');
}
}
addControl(name: string, control: FormControl): void {
this.form.addControl(name, control);
}
removeControl(name: string): void {
this.form.removeControl(name);
}
}
@Component({
selector: 'child-component',
template: `
<div>
<label for="firstName">First name:</label>
<input id="firstName" [formControl]="firstName" type="text"/>
</div>
<div>
<label for="lastName">Last name:</label>
<input id="lastName" [formControl]="lastName" type="text"/>
</div>
`,
directives: [REACTIVE_FORM_DIRECTIVES]
})
export class ChildComponent implements OnDestroy {
firstName: FormControl;
lastName: FormControl;
constructor(private _parent: FormControlContainer) {
this.firstName = new FormControl('', Validators.required);
this.lastName = new FormControl('', Validators.required);
this._parent.addControl('firstName', this.firstName);
this._parent.addControl('lastName', this.lastName);
}
ngOnDestroy() {
this._parent.removeControl('firstName');
this._parent.removeControl('lastName');
}
}
有更简单的方法将 formGroup 和 formControl 传递到下层组件 - 使用 @Inputs。
笨蛋: https://plnkr.co/edit/pd30ru?p=preview
在 FormComponent (MgForms) [main] 中我们做:
在代码中:
this.form = this.formBuilder.group(formFields);
在模板中:
<form [formGroup]="form" novalidate>
<div class="mg-form-element" *ngFor="let element of fields">
<div class="form-group">
<label class="center-block">{{element.description?.label?.text}}:
<div [ngSwitch]="element.type">
<!--textfield component-->
<div *ngSwitchCase="'textfield'"class="form-control">
<mg-textfield
[group]="form"
[control]="form.controls[element.fieldId]"
[element]="element">
</mg-textfield>
</div>
<!--numberfield component-->
<div *ngSwitchCase="'numberfield'"class="form-control">
<mg-numberfield
[group]="form"
[control]="form.controls[element.fieldId]"
[element]="element">
</mg-numberfield>
</div>
</div>
</label>
</div>
</div>
</form>
在 FieldComponent (MgNumberfield) [inner] 中我们做:
在代码中:
@Input() group;
@Input() control;
@Input() element;
在模板中:
<div [formGroup]="group">
<input
type="text"
[placeholder]="element?.description?.placeholder?.text"
[value]="control?.value"
[formControl]="control">
</div>
假设我从 angular2 应用生成的 html 如下所示:
<app>
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
<panel-component>
<mid-component>
<inner-component-with-inputs>
<input/>
<inner-component-with-inputs>
<mid-component>
</panel-component>
<panel-component>
<mid-component>
<inner-component-with-inputs>
<input/>
<inner-component-with-inputs>
<mid-component>
</panel-component>
<!-- many many many fields -->
<button type="submit">Submit</button>
</form>
</app>
如何设置外部 <form>
以便在提交时验证所有内部输入?我是否必须通过 myForm
通过 @Input()
从 panel-component
一直向下传递到 inner-component-with-inputs
?还是有别的办法?
在我的应用程序中,我有一个非常大的表单,包含多个面板、子面板、选项卡、模态框等,我需要能够在提交时立即验证它。
互联网上的所有教程和资源都只讨论跨越一个 component/template 的表格。
当涉及 parent/child 关系时,您将在整个 Angular 源代码中看到的一个常见模式是 parent 类型将自身添加为自身的提供者。这样做是允许 child 组件注入 parent。由于 hierarchical DI,在组件树 下 的整个过程中,只有一个 parent 组件的实例。下面是一个可能看起来像的例子
export abstract class FormControlContainer {
abstract addControl(name: string, control: FormControl): void;
abstract removeControl(name: string): void;
}
export const formGroupContainerProvider: any = {
provide: FormControlContainer,
useExisting: forwardRef(() => NestedFormComponentsComponent)
};
@Component({
selector: 'nested-form-components',
template: `
...
`,
directives: [REACTIVE_FORM_DIRECTIVES, ChildComponent],
providers: [formGroupContainerProvider]
})
export class ParentComponent implements FormControlContainer {
form: FormGroup = new FormGroup({});
addControl(name: string, control: FormControl) {
this.form.addControl(name, control);
}
removeControl(name: string) {
this.form.removeControl(name);
}
}
一些注意事项:
我们使用 interface/abstract parent (
FormControlContainer
) 有几个原因- 它将
ParentComponent
与ChildComponent
分离。 child 不需要了解特定ParentComponent
的任何信息。它所知道的只是FormControlContainer
和它所拥有的合同。 - 我们仅通过接口契约在
ParentComponent
上公开方法。
- 它将
我们只广告
ParentComponent
作为FormControlContainer
,所以后者是我们要注入的。我们以
formControlContainerProvider
的形式创建一个提供者,然后将该提供者添加到ParentComponent
。由于分层 DI,现在所有 children 都可以访问 parent.如果你不熟悉
forwardRef
,this is a great article
现在在child(ren)中你可以做到
@Component({
selector: 'child-component',
template: `
...
`,
directives: [REACTIVE_FORM_DIRECTIVES]
})
export class ChildComponent implements OnDestroy {
firstName: FormControl;
lastName: FormControl;
constructor(private _parent: FormControlContainer) {
this.firstName = new FormControl('', Validators.required);
this.lastName = new FormControl('', Validators.required);
this._parent.addControl('firstName', this.firstName);
this._parent.addControl('lastName', this.lastName);
}
ngOnDestroy() {
this._parent.removeControl('firstName');
this._parent.removeControl('lastName');
}
}
IMO,这是一个比通过 @Input
传递 FormGroup
更好的设计。如前所述,这是整个 Angular 来源的通用设计,因此我认为可以肯定地说这是一个可接受的模式。
如果你想让 child 组件更可重用,你可以使构造函数参数 @Optional()
.
下面是我用来测试上述例子的完整源代码
import {
Component, OnInit, ViewChildren, QueryList, OnDestroy, forwardRef, Injector
} from '@angular/core';
import {
FormControl,
FormGroup,
ControlContainer,
Validators,
FormGroupDirective,
REACTIVE_FORM_DIRECTIVES
} from '@angular/forms';
export abstract class FormControlContainer {
abstract addControl(name: string, control: FormControl): void;
abstract removeControl(name: string): void;
}
export const formGroupContainerProvider: any = {
provide: FormControlContainer,
useExisting: forwardRef(() => NestedFormComponentsComponent)
};
@Component({
selector: 'nested-form-components',
template: `
<form [formGroup]="form">
<child-component></child-component>
<div>
<button type="button" (click)="onSubmit()">Submit</button>
</div>
</form>
`,
directives: [REACTIVE_FORM_DIRECTIVES, forwardRef(() => ChildComponent)],
providers: [formGroupContainerProvider]
})
export class NestedFormComponentsComponent implements FormControlContainer {
form = new FormGroup({});
onSubmit(e) {
if (!this.form.valid) {
console.log('form is INVALID!')
if (this.form.hasError('required', ['firstName'])) {
console.log('First name is required.');
}
if (this.form.hasError('required', ['lastName'])) {
console.log('Last name is required.');
}
} else {
console.log('form is VALID!');
}
}
addControl(name: string, control: FormControl): void {
this.form.addControl(name, control);
}
removeControl(name: string): void {
this.form.removeControl(name);
}
}
@Component({
selector: 'child-component',
template: `
<div>
<label for="firstName">First name:</label>
<input id="firstName" [formControl]="firstName" type="text"/>
</div>
<div>
<label for="lastName">Last name:</label>
<input id="lastName" [formControl]="lastName" type="text"/>
</div>
`,
directives: [REACTIVE_FORM_DIRECTIVES]
})
export class ChildComponent implements OnDestroy {
firstName: FormControl;
lastName: FormControl;
constructor(private _parent: FormControlContainer) {
this.firstName = new FormControl('', Validators.required);
this.lastName = new FormControl('', Validators.required);
this._parent.addControl('firstName', this.firstName);
this._parent.addControl('lastName', this.lastName);
}
ngOnDestroy() {
this._parent.removeControl('firstName');
this._parent.removeControl('lastName');
}
}
有更简单的方法将 formGroup 和 formControl 传递到下层组件 - 使用 @Inputs。 笨蛋: https://plnkr.co/edit/pd30ru?p=preview
在 FormComponent (MgForms) [main] 中我们做:
在代码中:
this.form = this.formBuilder.group(formFields);
在模板中:
<form [formGroup]="form" novalidate>
<div class="mg-form-element" *ngFor="let element of fields">
<div class="form-group">
<label class="center-block">{{element.description?.label?.text}}:
<div [ngSwitch]="element.type">
<!--textfield component-->
<div *ngSwitchCase="'textfield'"class="form-control">
<mg-textfield
[group]="form"
[control]="form.controls[element.fieldId]"
[element]="element">
</mg-textfield>
</div>
<!--numberfield component-->
<div *ngSwitchCase="'numberfield'"class="form-control">
<mg-numberfield
[group]="form"
[control]="form.controls[element.fieldId]"
[element]="element">
</mg-numberfield>
</div>
</div>
</label>
</div>
</div>
</form>
在 FieldComponent (MgNumberfield) [inner] 中我们做:
在代码中:
@Input() group;
@Input() control;
@Input() element;
在模板中:
<div [formGroup]="group">
<input
type="text"
[placeholder]="element?.description?.placeholder?.text"
[value]="control?.value"
[formControl]="control">
</div>