我正在尝试生成以下对象的表单值:
{
party: 'Birthday Party"
guests: [
{firstName: 'John', lastName: 'Smith'}
{firstName: 'Mona', lastName: 'Lisa'}
]
}
我使用FormBuilder进行以下表单控件:
this.form = this.fb.group({
party: '',
guests = this.fb.array([{
firstName: '',
lastName: '',
}])
});
我的HTML:
<form>
<input type="text" placeholder="party" formControlName="party">
<div formArrayName="guests">
<input type="text" placeholder="first" formControlName="firstName">
<input type="text" placeholder="last" formControlName="lastName">
</div>
<button>+ADD GUEST</button>
</form>
我收到以下错误:
Error: Cannot find control with path: 'guests -> firstName'
Error: Cannot find control with path: 'guests -> lastName'
我不知道如何处理ADD GUEST (click)
的{{1}}函数。我该如何做到&#39;追加&#39;表格中的另一位客人?
如何添加验证器以确保在表单有效之前至少有一个访客?
答案 0 :(得分:1)
您将错误的模型传递给FormBuilder.array。
这是正确的方式:
public form = this.fb.group({
party: 'test',
guests: this.fb.array([
this.fb.group( {firstName: 'firstName', lastName: 'lastName'})
])
});
答案 1 :(得分:-2)