为了捕获和监视输入值,我建议您将 ngModel 指令添加到动态表单内的所有 input 控件中。这将自动为每个input 创建一个FormControl 实例,您可以将其添加到动态FormGroup:
注意:您也可以通过访问inputElement.value 来获取输入值,但是
您必须收听input 事件才能观察变化
html
<filter-form (onSubmit)="onSubmit($event)">
<input type="text" placeholder="0.00" propertyName="1" ngModel/>
<input type="text" placeholder="0.00" propertyName="2" ngModel/>
<input type="text" placeholder="0.00" propertyName="3" ngModel/>
<mat-form-field>
<input matInput type="text" placeholder="0.00" propertyName="4" ngModel/>
</mat-form-field>
</filter-form>
您可以通过将 NgModel 实例注入到您的自定义指令中来获取它:
@Directive({
selector: "input"
})
export class FocusDirective {
@Input() propertyName: string;
constructor(public ngModel: NgModel) {}
}
现在,您可以将 FormControl 实例添加到您的 formGroup:
ngAfterContentInit(): void {
console.log("ngAfterContentInit::input is: ", this.items);
this.items.toArray().forEach(x => {
this.formGroup.addControl(
x.propertyName,
x.ngModel.control <--------------------------- this one
);
});
}
为了获得所有ContentChildren,无论嵌套级别如何,您都必须使用descendants 选项:
@ContentChildren(FocusDirective, { descendants: true }) items: QueryList<FocusDirective>;
Forked Stackblitz