[英]Angular2 template driven sub form component with validation
我有一個模板驅動的表單,其中包含一個ngFor
包含的一組輸入。
我試圖將重復的'子組'分成它自己的子組件,但是我很難讓父ngForm
包含子組件中包含的驗證。
這是我所說的簡化版本:
父模板 :
<form #parentForm="ngForm">
<input name="firstName" ngModel required>
<input name="lastName" ngModel required>
<child-component *ngFor="let child of children;"></child-component>
</form>
兒童模板 :
<div>
<input name="foo" required ngModel>
<input name="bar" required ngModel>
</div>
我無法讓父母表格接受required
的兒童輸入。 我嘗試讓孩子處於自己的形式,並將#parentForm
實例傳遞給孩子,並讓孩子調用:
this.parentForm.addFormGroup(this.childForm.form)
但這仍然行不通。
我也有孩子這樣做,反過來父母獲取子表單的ContentChildren
並將每個子表單添加到表單,但仍然驗證不起作用。
我知道我可以讓子組件實現ControlValueAccessor
但是我需要實現一個自定義驗證器,我不想這樣做,因為驗證都不是新的,只是required
它。
請幫我弄清楚為什么我不能向父母添加子表單並讓它使用孩子的驗證。
一種可能的解決方案可能是從子組件到父組件的添加控件,如下所示:
child.component.ts
@Component({
selector: 'child-component',
template: `
<div>
<input name="foo" required ngModel>
<input name="bar" required ngModel>
</div>
`
})
export class ChildComponent {
@ViewChildren(NgModel) controls: QueryList<NgModel>;
constructor(private parentForm: NgForm) { }
ngAfterViewInit() {
this.controls.forEach((control: NgModel) => {
this.parentForm.addControl(control);
});
}
}
你可以使用屬性綁定和@Input來解決你的問題
<form #parentForm="ngForm">
<input name="firstName" ngModel required>
<input name="lastName" ngModel required>
<child-component #parentForm.childForm="ngForm" [children]="children"></child-component>
</form>
在你的
將輸入變量聲明為
@Input() children:any[]=[];
修改模板如下
<div *ngFor="let child of children;"> <input name="foo" required [(ngModel)]="child.foo"/> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.