Angular 11 变更检测问题

Angular 11 change detection issue

我的 html 视图有一个情况,我正在更新 material 滑块的绑定,如下所示:

 <mat-slider
    [disabled]="isLoading || (isUpdating$ | async)"
    color="primary"
    min="0"
    max="100"
    step="1"
    [ngModel]="myService.thresholdvalue$ | async"
    (change)="maskChanged($event)"
  ></mat-slider>

但是当我的子组件通过 this.thresholdValueSub.next(value); 调用服务更新它时,我获取经典更改检测错误:

ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '3'

我认为我可以使用 async 来解决它,但我错了:

[ngModel]="myService.maskThreshold$ | async"

然后我想我会 运行 如下更改检测(在更新值时在我的父组件上):

ngOnInit(): void {

  this.subscriptions
    ...
    .add(this.myService.thresholdValue$.subscribe(res => {
      this.thresholdValue = res;
      if (res !== undefined) {
        this.changeDetector.markForCheck();
      }
    }));
 }

又错了!我仍然收到更改检测错误。

我是否应该 post 更多代码使其更清晰?

谢谢。

******** 更新 *********

从 html 中删除异步管道,因为我已经在 ts 文件中进行了替换:

  <mat-slider
    [disabled]="isLoading || (isUpdating$ | async)"
    color="primary"
    min="0"
    max="100"
    step="1"
    [(ngModel)]="mosaicService.maskThreshold$"
    (change)="maskChanged($event)"
  ></mat-slider>

运行 订阅时更改检测:

.add(this.mosaicService.maskThreshold$.subscribe(res => {
    this.maskValue = res;
    if (res !== undefined) {
      this.changeDetector.detectChanges();
    }
  })

不再有变化检测错误! :-)

我最终删除了 HTML 中的 async 管道,因为我已经在 ts 文件中订阅了。所以我的错误是订阅了两次。 :-(

因此,有了这行更改检测器代码,我就可以开始了!

 this.changeDetector.detectChanges();