banner
ZetoHkr

ZetoHkr

摸🐟从未停止,努力从未开始
github

修復 “Expression has changed after it was checked”

修復 “Expression has changed after it was checked. Previous value: 'ngIf: true'. Current value: 'ngIf: false'.”#

報錯內容#

Expression has changed after it was checked. Previous value: 'ngIf: true'. Current value: 'ngIf: false'.

概述#

雖然這個報錯幾乎不會影響正常使用,但是看著 Console 中有報錯就很難受(
所以想解決這個問題。

開始解決#

  • 首先通過這個報錯我們大概可以知道,是由於在 Angular 檢查值的時候,發現了原有的值與新的值不一致導致的

  • 既然 Angular 不能自己去更新,只好我們去幫他更新了,代碼如下:

    import { AfterContentChecked } from '@angular/core';
    // ... 其他代碼
    @Component({
        selector: 'app-test',
        templateUrl: './test.component.html'
    })
    export class TestComponent implements AfterContentChecked {
        // ... 其他代碼
        public constructor(
                private titleService: Title,
                public layout: LayoutService,
                // 更新檢查器
                private cdr: ChangeDetectorRef,
        ) {
            // ... 其他代碼
        }
        
        // 檢查之後,我們再觸發一次更新檢查
        ngAfterContentChecked(): void {
            this.cdr.detectChanges();
        }
}
  • 這樣,我們這個問題就解決了
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。