Angular 将字段更改为必填项会引发ExpressionChangedAfterCheckedError
我试图在点击按钮时创建一个必填字段。当我尝试将字段更改为“必需”时,会出现以下错误:Angular 将字段更改为必填项会引发ExpressionChangedAfterCheckedError,angular,typescript,angular-material,Angular,Typescript,Angular Material,我试图在点击按钮时创建一个必填字段。当我尝试将字段更改为“必需”时,会出现以下错误: core.js:6406 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'disabled': 'false'. Current value: 'true'. 这是我的控制器代码: ngOnInit() { t
core.js:6406 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'disabled': 'false'. Current value: 'true'.
这是我的控制器代码:
ngOnInit() {
this.exportTypeForm = new FormGroup({
exportType: new FormControl('page', Validators.required),
email: new FormControl('')
});
}
onExportTypeChange(e: MatRadioChange): void {
if (e.value === 'list') {
this.exportTypeForm.controls['email'].setValidators(Validators.required);
this.exportTypeForm.updateValueAndValidity();
this.showEmailField = true;
} else {
this.exportTypeForm.controls['email'].clearValidators();
this.exportTypeForm.updateValueAndValidity();
this.showEmailField = false;
}
}
以及HTML:
<form *ngIf="exportTypeForm" [formGroup]="exportTypeForm">
<mat-radio-group formControlName="exportType" (change)="onExportTypeChange($event)">
<mat-radio-button value="page">This page</mat-radio-button>
<mat-radio-button class="ml-4" value="list">All pages</mat-radio-button>
</mat-radio-group>
<mat-form-field appearance="outline" *ngIf="showEmailField" class="mb-4">
<mat-label>Email Address</mat-label>
<input matInput formControlName="email" />
<mat-hint>An email with a link to the excel file will be sent to this address</mat-hint>
</mat-form-field>
</form>
本页
所有页面
电子邮件地址
带有excel文件链接的电子邮件将发送到此地址
我不确定还有什么其他方法可以做到这一点。有人能帮我找到一种方法让它工作吗?所以我发现这是因为我是如何在
updateValueAndValidity()
方法上运行逻辑的。我在整个表单上调用它,但它不起作用。您需要在单个控件上调用它
以下是工作代码:
onExportTypeChange(e: MatRadioChange): void {
if (e.value === 'list') {
this.exportTypeForm.get('email').setValidators(Validators.required);
this.exportTypeForm.get('email').updateValueAndValidity();
this.showEmailField = true;
} else {
this.exportTypeForm.get('email').clearValidators();
this.exportTypeForm.get('email').updateValueAndValidity();
this.showEmailField = false;
}
}
您是否尝试将
ngOnInit
中的逻辑移动到ngAfterViewInit
?是否尝试使用ChangeDetectorRef
?