网站搜索

typescript - Angular 17:在新控制流上出现 NG0100


几周前,我们将我们的 Angular 应用迁移到了 Angular 17。在此过程中,我们还使用了 Angular CLI 命令将所有控制流更改为新的内置控制流。这运行良好,乍一看,一切都像以前一样正常。

然而,就在几天前,我遇到了一个“NG0100: Expression has changed after it was checked”的问题,而在变更之前并没有错误。我正在努力寻找解决这个问题的方法。

我们有一个带有 BehaviorSubject 的组件。这个 BehaviorSubject 在子组件中使用,用于向父组件提供其加载状态的信息。在 HTML 中,这看起来像这样:

@if (childComponentLoadingState$ | async; as childComponentLoadingState) {
  ...
  
  <mat-stepper linear #myStepper>
    <mat-step [completed]="isFirstStepCompleted(childComponentLoadingState)">
      ...
      <my-child-component [componentLoadingState$]="childComponentLoadingState$">
      </my-child-component>
      ...
    </mat-step> 
    ...
  </mat-stepper>

  ...
}

只要我们使用 *ngIf,这就能正常工作,并且我们没有收到任何错误。现在在提供的实现中,我们在 mat-step 标签的那一行收到了“NG0100: Expression has changed after it was checked”的错误。

有人知道现在为什么会出现错误以及我们如何解决它吗?谢谢你的帮助!:)

答案#1

首先,新的 Angular 控制流处于开发者预览阶段,因此 不是 稳定的控制流。如果你希望使用实验性的控制流,NG0100 与变更检测有关,在不了解你的代码的情况下,我建议如下:

  1. 在内容被检查后手动 detectChanges
  2. 在你的 subject 上使用 RXJS 操作符来 detectChanges,例如 pipe 和 tap
  3. 恢复使用 *ngIf 指令,因为它能解决你的问题并且很稳定
import { ChangeDetectorRef } from '@angular/core';
    
constructor( private cdr: ChangeDetectorRef ) {}   
    
ngAfterContentChecked() {
    this.cdr.detectChanges();
}