我通过REST-API获取数据。借助这些数据,我为表格生成单选按钮。只要表单无效,就会禁用Submit-Button。由于检索数据需要一些时间,因此表单的有效性会发生变化。这会引发ExpressionChangedAfterItHasBeenCheckedError
。我该如何解决这个问题?目前,我有点困惑。
形式:
<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>
组件:
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]))
}
}
答案 0 :(得分:0)
只有在使用布尔标志获取所有数据时才能显示视图,它应该可以防止错误,如下所示:
<form #Form="ngForm" [formGroup]="formGroup" *ngIf="readyToShow">
在组件中:
readyToShow = false;
createForm() {
for (let i = 0; i < this.data.length; i++) {
this.formArray.push(new FormControl('', [Validators.required]))
}
this.readyToShow = true;
}