2017-04-21 54 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