2017-02-22 27 views
1

在模式驅動形式中,我有幾個屬性。一個屬性包含一個數組。我想顯示這個數組中的表:以模型驅動形式訪問數組

<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?如果是的話 - >我會如何實現這一目標?

回答

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>