FormArray是FormGroup的变体.关键区别在于,它的数据被序列化为数组(而不是在FormGroup中被序列化为对象).当您不知道组中会有多少控件(如动态表单)时,这可能特别有用.
让我试着用一个简单的例子来解释.比如说,你有一个表格,可以记录顾客的披萨订单.你可以放置一个按钮,让他们添加和删除任何特殊请求.以下是组件的html部分:
<section>
<p>Any special requests?</p>
<ul formArrayName="specialRequests">
<li *ngFor="let item of orderForm.controls.specialRequests.controls; let i = index">
<input type="text" formControlName="{{i}}">
<button type="button" title="Remove Request" (click)="onRemoveSpecialRequest(i)">Remove</button>
</li>
</ul>
<button type="button" (click)="onAddSpecialRequest()">
Add a Request
</button>
</section>
下面是定义和处理特殊请求的Component类:
constructor () {
this.orderForm = new FormGroup({
firstName: new FormControl('Nancy', Validators.minLength(2)),
lastName: new FormControl('Drew'),
specialRequests: new FormArray([
new FormControl(null)
])
});
}
onSubmitForm () {
console.log(this.orderForm.value);
}
onAddSpecialRequest () {
this.orderForm.controls
.specialRequests.push(new FormControl(null));
}
onRemoveSpecialRequest (index) {
this.orderForm.controls['specialRequests'].removeAt(index);
}
FormArray提供了比FormGroup更多的灵活性,因为使用"Push"、"Insert"和"removeAt"操作FormControls比使用FormGroup的"addControl"、"removeControl"、"setValue"等更容易.FormArray方法确保在窗体的层次 struct 中正确跟踪控件.
希望这能帮上忙.