我使用包含FormGroups
的FormArray的以下表单 <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>
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('value')会引发错误。
那么如何访问表单控件的值?
答案 0 :(得分:11)
您可以尝试从网址组获取控制权
<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 强>
答案 1 :(得分:6)
试试这个:
screenForm.get('url').value
如果这不起作用,我将不得不看到整个表单构建器进一步提供帮助。