以模型驱动的形式访问数组

时间:2017-02-22 11:22:52

标签: angular

在模态驱动的形式中,我有几个属性。一个属性包含一个数组。我想在表格中显示这个数组:

<form class="form-horizontal" [formGroup]="reproOrderForm">
 ...
 <div class="col-md-12" formArrayName="anyArray">
   <table class="table table-striped table-condensed">
     <tr>
       <th>col1</th>
       <th>col2</th>
     </tr>
     <tr *ngFor="let elem of reproOrderForm.controls.anyArray.controls;let i = index;" [formGroupName]="i">
       <td>{{i+1}}</td>
       <td>{{elem.value.anyValue}}</td>
     </tr>
   </table>
 </div>
 ...
</form>

在我的component.ts中我定义了这个:

ngOnInit() {
   this.reproOrderForm = this.formBuilder.group({
     ...
     anyArray: this.formBuilder.array([
       this.formBuilder.group({
         anyValue: []
       })
     ])
   });
}

我的问题是:是否可以比在HTML中更容易地访问此数组?如果是这样的话 - &gt;我怎么做到这一点?

1 个答案:

答案 0 :(得分:2)

如果模板简洁是您唯一关注的问题,您可以将myForm.controls.anyArray(或甚至myForm.controls.anyArray.controls)分配给自己的类属性,例如:

export class MyComponent {
  reproOrderForm: FormGroup;
  formArray: FormArray;

  ngOnInit() {
    // Assign the array first
    this.formArray = this.formBuilder.array([
      this.formBuilder.group({
        anyValue: []
      })
    ]);
    // Then assign the form.
    this.reproOrderForm = this.formBuilder.group({
       anyError: this.formArray
     });
  }
}

然后在你的模板中:

<tr *ngFor="let elem of formArray.controls;let i = index;">...</tr>