擴充診斷

ngSkipHydration 應該是靜態屬性

ngSkipHydration 是一個特殊屬性,用來向 Angular 表示特定元件應該退出水合(hydration)機制。 這項診斷會確保 ngSkipHydration 屬性是以靜態方式設定,且其值為 "true" 或空值。

import {Component} from '@angular/core';

@Component({
  template: `<user-viewer ngSkipHydration="hasUser" />`,
})
class MyComponent {
  hasUser = true;
}

這樣寫有什麼問題?

ngSkipHydration 是 Angular 實作的特殊屬性,必須能被靜態分析,Angular 才能在編譯時期知道某個元件是否需要水合。

我應該怎麼做?

使用 ngSkipHydration 時,請確認它是設定為靜態屬性(也就是不要使用 Angular 範本繫結語法)。

import {Component} from '@angular/core';

@Component({
  template: `
    <user-viewer ngSkipHydration />
    <user-viewer ngSkipHydration="true" />
  `,
})
class MyComponent {}

如果需要條件判斷,可以把元件包在 *ngIf 裡面。

import {Component} from '@angular/core';

@Component({
  template: `
    <div *ngIf="hasUser; else noUser">
      <user-viewer ngSkipHydration />
    </div>

    <ng-template #noUser>
      <user-viewer />
    </ng-template>
  `,
})
class MyComponent {}

設定需求

任何擴充診斷要發出訊息,都必須啟用 strictTemplates。 skipHydrationNotStatic 除了 strictTemplates 之外,沒有其他額外需求。

如果無法避免,該怎麼辦?

可以透過編輯專案的 tsconfig.json 檔案來停用這項診斷:

{
  "angularCompilerOptions": {
    "extendedDiagnostics": {
      "checks": {
        "skipHydrationNotStatic": "suppress"
      }
    }
  }
}

詳情請見擴充診斷設定。