2017-02-22 5 views
1

In einer modal gesteuerten Form habe ich mehrere Eigenschaften. Eine Eigenschaft enthält ein Array. Ich möchte in einer Tabelle dieses Array anzuzeigen:Access Array in einer modellgesteuerten Form

<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> 

in meinem component.ts I definiert haben dies:

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

Meine Frage ist: Ist es möglich, diese Anordnung leichter zugänglich als ich in mein HTML? Und wenn ja -> Wie würde ich das erreichen?

Antwort

2

Wenn Vorlage Prägnanz Ihre einzige Sorge ist, könnten Sie myForm.controls.anyArray (oder sogar myForm.controls.anyArray.controls) in seine eigene Klasse Eigenschaft zuweisen, z.B .:

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 
    }); 
    } 
} 

Und dann in der Vorlage:

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