MatExpansionPanel 表达式在检查错误“mat-expanded:true”后已更改

2024-01-08

我有一个角度材质扩展面板查询列表:

  @ViewChildren(MatExpansionPanel)
  matExpansionPanelQueryList: QueryList<MatExpansionPanel>;

和一个简单的数组:

questions: [];

扩展面板是用一个*ngFor:简化例如:

   <ng-container *ngFor="let question of questions>
            <mat-expansion-panel
               ...

当我扩展问题数组时,我想打开最后一个扩展面板。

     extendQuestion() {
        this.matExpansionPanelQueryList.changes.subscribe(
          change => {
            change.last.open();
          }
        );

        this.questions.push('some-new-item');
      }

这工作得很好 - 我将一个项目插入到数组中,
ExpansionPanels 重新渲染,创建一个新面板并实际打开 - 我的问题是它在控制台中生成以下错误:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has 
changed after it was checked. Previous value: 'mat-expanded: false'. Current 
value: 'mat-expanded: true'.

有什么办法可以避免这种情况吗?
我尝试过使用changeDetectorRef and markForCheck()在订阅中,但错误消息并没有消失(老实说,我 100% 确定这里的确切问题是什么)。

Update: Stackblitz 问题示例(单击“+”按钮) https://stackblitz.com/edit/angular-material-3hm2z7


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');
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MatExpansionPanel 表达式在检查错误“mat-expanded:true”后已更改 的相关文章

随机推荐