From 角度深度 https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4:
这是一种警告机制,旨在防止模型数据和 UI 之间出现不一致,从而不会在页面上向用户显示错误或旧数据。
正在运行的 Angular 应用程序是一个组件树。在变更检测期间,Angular 对每个组件执行检查,其中包括按指定顺序执行的以下操作:
- 更新所有子组件/指令的绑定属性
- 在所有子组件/指令上调用 ngOnInit、OnChanges 和 ngDoCheck 生命周期挂钩
- 更新当前组件的 DOM
- 为子组件运行更改检测
- 为所有子组件/指令调用 ngAfterViewInit 生命周期钩子
每次操作后,Angular 都会记住它用于执行操作的值。它们存储在组件视图的 oldValues 属性中。
您可能希望在 DOM 更新操作之前触发组件的生命周期挂钩。
这应该对你有用:
您可以添加一个constructor
用于变更检测(cd)并在之后调用它change.last.open();
import {ChangeDetectorRef, Component, OnInit, QueryList, ViewChildren} from '@angular/core';
import {MatDialog, MatExpansionPanel} from '@angular/material';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
questions = ['first', 'second'];
constructor(private cd: ChangeDetectorRef) {
}
@ViewChildren(MatExpansionPanel) matExpansionPanelQueryList: QueryList<MatExpansionPanel>;
extendQuestion() {
this.matExpansionPanelQueryList.changes.subscribe(
change => {
change.last.open();
this.cd.detectChanges();
}
);
this.questions.push('some-new-item');
}
}