当涉及父/子关系时,您将在整个 Angular 源代码中看到一个常见模式,即父类型将自身作为提供者添加到自身。这样做是允许子组件注入父组件。由于hierarchical DI,在组件树向下的整个过程中只有一个父组件实例。下面是一个可能看起来像的示例
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);
}
}
一些注意事项:
-
我们使用接口/抽象父级 (FormControlContainer) 有几个原因
- 它将
ParentComponent 与ChildComponent 分离。孩子不需要知道具体的ParentComponent。它只知道FormControlContainer 和已有的合同。
- 我们只通过接口契约公开
ParentComponent 上想要的方法。
我们只宣传ParentComponent为FormControlContainer,所以我们将注入后者。
我们以formControlContainerProvider 的形式创建一个提供程序,然后将该提供程序添加到ParentComponent。由于分层 DI,现在所有子级都可以访问父级。
如果您对forwardRef不熟悉,this is a great article
现在在孩子(们)你可以这样做
@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,这是一个比通过@Inputs 传递FormGroup 更好的设计。如前所述,这是整个 Angular 源代码中的常见设计,所以我认为可以肯定地说这是一种可接受的模式。
如果您想让子组件更可重用,可以将构造函数参数设为@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');
}
}