![](/img/trans.png)
[英]angular 6 "ExpressionChangedAfterItHasBeenCheckedError" in reactive form dynamic form validation add and remove
[英]Angular form with dynamic clarity tabs get ExpressionChangedAfterItHasBeenCheckedError after add tab
我有带有动态标签的反应式 angular 表单。 首先 - 带有字段的选项卡,然后是带有添加选项卡按钮的选项卡。 如果我在表单中添加选项卡,我会收到错误 ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it is checked。 以前的值:“活动:真”。 当前值:“活动:假”。
很明显改变了标签激活状态,所以我收到了这个错误。 尝试使用 setTimeout - 在删除选项卡中它正在工作 - 没有错误。 但是在添加 - 它有时会显示 - 当活动选项卡没有持续时会出现。 有时我会激活 addTab - 但我手动将其更改为 false。
onAdd(event) {
event.stopPropagation();
const info = this.listGroupDef();
this.infoList.push(this.fb.group(info));
this.infoList.markAsDirty();
this.tabs.push(false);
setTimeout(() => {
this.addTab = false;
this.tabs[this.tabs.length - 1] = true;
}, 0);
}
onDelete(event, index: number) {
setTimeout(() => {
if (this.tabs[index]) {
this.tabs[0] = true;
}
this.tabs.slice(index, 1);
this.infoList.removeAt(index);
}, 0);
event.stopPropagation();
}
<clr-tabs>
<clr-tab *ngFor="let InfoFormGroup of InfoList.controls; let infoIndex = index">
<button clrTabLink>title<clr-icon shape="times" (click)="onDelete($event, infoIndex)"></clr-icon></button>
<ng-template [(clrIfActive)]="tabs[infoIndex]">
<clr-tab-content>
angular reactive form
</clr-tab-content>
</ng-template>
</clr-tab>
<clr-tab>
<button clrTabLink (click)="onAdd($event)"><clr-icon shape="plus-circle"></clr-icon></button>
<ng-template [(clrIfActive)]="addTab">
<clr-tab-content>
</clr-tab-content>
</ng-template>
</clr-tab>
</clr-tabs>
您能否提供有关您的项目的任何其他信息? 出现此错误的主要原因有以下三个:
您正在 AfterViewInit 中执行代码,这在使用 ViewChild 时经常发生,因为在调用 AfterViewInit 之前它是未定义的。
您正在直接操作 DOM(例如使用 jQuery)。 Angular 无法始终检测到这些变化并做出正确反应。
当您在 HTML 模板中调用函数时,它也可能由于竞争条件而发生。
请遵循这三个规则并在您的应用程序中检测相应的点。
您的错误说明了发生的变化,而角度的变化检测器没有记录。
请阅读以下博客,它解释了ChangeDetectionStrategy
在您的代码中,您可以在更改active
属性后显式调用detectChanges
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.