FormGroup:
A FormGroup aggregates the values of each child FormControl into one
object,with each control name as the key.06000
A FormArray aggregates the values of each child FormControl into an
array.06001
应该何时使用另一个?
FormArray是FormGroup的变体.关键的区别在于它的数据被序列化为一个数组(而不是在FormGroup的情况下被序列化为一个对象).当您不知道组中将存在多少控件(如动态表单)时,这可能特别有用.
让我试着通过一个简单的例子来解释.比如,您有一个表单,您可以在其中捕获客户对Pizza的订单.然后你放置一个按钮让他们添加和删除任何特殊请求.这是组件的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>
这是定义和处理特殊请求的组件类:
- 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”比使用FormGroup的“addControl”,“removeControl”,“setValue”等更容易操作FormControl.FormArray方法确保控件是在表单的层次结构中正确跟踪.
希望这可以帮助.