2017-04-21 55 views
2

我有以下形式的FormArray含FormGroups如何獲得angular2

<form [formGroup]="screenForm" novalidate> 

    <div formArrayName="iPhoneScreenshots" class="row"> 
    <div *ngIf="screenForm.controls.iPhoneScreenshots?.length > 0"> 
     {{screenForm.controls.iPhoneScreenshots?.length }} 
     <div *ngFor="let url of screenForm.controls.iPhoneScreenshots.controls; let i=index"> 
     <div [formGroupName]="i"> 
      <input class="form-control" formControlName="url"> 
      <img src="{{app.screenshotUrls[i]}}" class="rounded img-fluid app-screen" style="height:200px"/> 
     </div> 
     </div> 
    </div> 
    </div> 
</form> 
一個FormControl的價值

的URL值來自數組這是越來越回調通過API 填充我設置值:

private setScreenShots(app: ItunesApp): void { 
if (app.hasOwnProperty('screenshotUrls')) { 
    const screenShots = app.screenshotUrls.map(url => { 
     return this.fb.group({ 
     url: [url, Validators.required] 
     }); 
    } 
); 
    const screenShotsArray = this.fb.array(screenShots); 
    this.screenForm.setControl('iPhoneScreenshots', screenShotsArray); 
} 
} 

初始數組爲空

private createForm() { 
    this.appSiteForm = this.fb.group({ 
    title: ['', Validators.required] 
}); 

this.screenForm = this.fb.group({ 
    iPhoneScreenshots: this.fb.array([]), 
}); 

}

這行代碼看起來很奇怪,我

img src="{{app.screenshotUrls[i]}}" 

我這樣做,因爲url.value()或url.get( '值')引發的錯誤。

那麼如何訪問表單控件的值呢?

回答

4

你可以嘗試從URL組得到控制

<div *ngFor="let urlGroup of screenForm.controls.iPhoneScreenshots.controls; let i=index"> 
    <div [formGroupName]="i"> 
     <input class="form-control" formControlName="url"> 
     <img [src]="urlGroup.get('url').value" /> 
    </div> 
</div> 

Plunker Example

+0

就是這樣。完美的作品。你能指點我的文檔,因爲我沒有在angular.io上給出的例子中看到這個 – dc10

0

試試這個:

screenForm.get('url').value 

如果這樣做不行,我得看看你的整個表單生成提供進一步協助。

+0

'無法讀取屬性「價值」 null'的我也更新了方法的CreateForm,你會看到有隻是另一種形式。 – dc10