[英]How to get the value of a FormControl in angular2
I have the following form with an FormArray containing FormGroups 我有一个包含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>
the url values come from an array which is getting populated via API in the callback I set the values: 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);
}
}
initial array is empty 初始数组为空
private createForm() {
this.appSiteForm = this.fb.group({
title: ['', Validators.required]
});
this.screenForm = this.fb.group({
iPhoneScreenshots: this.fb.array([]),
});
} }
this code line looks very strange to me 这段代码对我来说很奇怪
img src="{{app.screenshotUrls[i]}}"
I am doing this since url.value() or url.get('value') raises errors. 我这样做是因为url.value()或url.get('value')会引发错误。
So how can I access the value of a form control? 那么如何访问表单控件的值呢?
You can try to get control from url group 您可以尝试从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>
Try this: 尝试这个:
screenForm.get('url').value
If this doesn't work, I'll have to see your entire form builder to assist further. 如果这不起作用,我将不得不看到整个表单构建器进一步提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.