簡體   English   中英

Angular 11 變更檢測問題

[英]Angular 11 change detection issue

我在我的 html 視圖中有一個情況,我正在更新材質滑塊的綁定,如下所示:

 <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();
      }
    }));
 }

又錯了 ! 我仍然收到更改檢測錯誤。

我應該發布更多代碼以使其更清晰嗎?

謝謝你。

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

從 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM