[英]Angular 4 Load Data Service for Form throws ExpressionChangedAfterItHasBeenCheckedError
I'm getting data through an REST-API. 我正在通过REST-API获取数据。 With the help of this data I generate radio buttons for a form. 借助这些数据,我为表单生成了单选按钮。 As long as the form is not valid, the Submit-Button is disabled. 只要表单无效,就禁用“提交按钮”。 Since retrieving the data takes a little time, the validity of the form changes. 由于检索数据需要一些时间,因此表单的有效性会发生变化。 This throws an ExpressionChangedAfterItHasBeenCheckedError
. 这将引发ExpressionChangedAfterItHasBeenCheckedError
。 How can I fix the problem? 我该如何解决该问题? At the moment I'm a bit baffled. 此刻我有点困惑。
Form: 形成:
<form #Form="ngForm" [formGroup]="formGroup">
<div formArrayName="formArray">
<div *ngFor="let temp of data,let i=index">
<label [for]="i">
<input [name]="i" type="radio" [formControlName]="i" [(ngModel)]="selection" [value]="temp"/>
{{temp.name}}
</label>
</div>
</div>
<buttontype="button" (click)="goToPrevious(Form)">Back</button>
<button mat-raised-button type="button" [disabled]="!formGroup.valid"
(click)="goToNext(Form)">Next
</button>
</form>
Component: 零件:
this.formGroup = new FormGroup({
formArray: this.formArray = new FormArray([])
});
this.commonService.getData().subscribe(data => {
this.data= data;
this.createForm();
}
);
createForm() {
for (let i = 0; i < this.data.length; i++) {
this.formArray.push(new FormControl('', [Validators.required]))
}
}
You can show the view only when all data is fetched using boolean flag, it should prevent the error, like this: 仅当使用boolean标志获取所有数据时,您才可以显示视图,这样可以防止出现错误,如下所示:
<form #Form="ngForm" [formGroup]="formGroup" *ngIf="readyToShow">
And in component: 在组件中:
readyToShow = false;
createForm() {
for (let i = 0; i < this.data.length; i++) {
this.formArray.push(new FormControl('', [Validators.required]))
}
this.readyToShow = true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.