我试图定义一个包含动态表单(使用 ReactiveForms)的组件,用户应该能够在其中添加/删除控件。
控件可以采用多种形式,并且必须在组件外部定义,因此我认为 TemplateRef 最适合这种情况。
我正在努力寻找一种通过使用 formControlName 将外部定义的控件绑定到内部表单的方法
这是实施的开始:
// expandable.component.ts
[...]
@Component({
selector: 'expandable',
templateUrl: 'app/component/common/expandable/expandable.component.html',
styleUrls: ['app/component/common/expandable/expandable.component.css']
})
export class ExpandableComponent {
@ContentChild('childTemplate') childTemplate: TemplateRef<any>;
@Input() children: Array<any>;
public form: FormGroup;
constructor(private _changeDetector: ChangeDetectorRef,
private _formBuilder: FormBuilder) {
this.children = [];
}
public ngOnInit(): void {
this.form = this._formBuilder.group({
children: this._formBuilder.array([])
});
const arrayControl = <FormArray>this.form.controls['children'];
this.children.forEach(child => {
const group = this.initChildForm();
arrayControl.push(group);
});
}
private initChildForm(): AbstractControl {
return this._formBuilder.group({
key: ['Initial Key', [Validators.required]],
value: ['Initial Value', [Validators.required]]
});
}
public addChild(): void {
const control = <FormArray>this.form.controls['children'];
control.push(this.initChildForm());
this._changeDetector.detectChanges();
}
}
-
<!-- expandable.component.html -->
<form [formGroup]="form">
<div class="form-group">
<div formArrayName="children">
<div *ngFor="let child of form.controls.children.controls; let i=index">
<div [formGroupName]="i">
<template
[ngTemplateOutlet]="childTemplate"
[ngOutletContext]="{ $implicit: child }"></template>
</div>
</div>
</div>
</div>
<a (click)="addChild()">Add Child</a>
</form>
尝试在外部定义模板:
<expandable>
<template #childTemplate>
<input class="form-control"
formControlName="value" />
</template>
</expandable>
我天真地尝试将 formControlName 绑定到从 outer 隐式传递的上下文,但没有运气,因为我收到“无法找到名称为“值”的控件”。理想情况下,我希望能够将 formControlName 绑定到expandable.component.html
相反,但我也看不出有什么办法可以做到这一点。
对此有什么想法吗?