【发布时间】:2017-07-10 05:04:36
【问题描述】:
我有一个模板驱动的表单,其中包含一组输入,包含在 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 的。
请帮我弄清楚为什么我不能将子表单添加到父表单并让它使用子表单的验证。
【问题讨论】:
标签: javascript forms validation angular typescript