擴充診斷

Track 函式未被呼叫

這項診斷會偵測 @for 區塊中 track 函式未被呼叫的情況。

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

@Component({
  template: `@for (item of items; track trackByName) {}`,
})
class Items {
  protected trackByName(item) {
    return item.name;
  }
}

這樣寫有什麼問題?

@for 區塊需要為可迭代物件中的每個項目建立唯一識別,才能在項目重新排序、新增項目或移除既有項目時,正確地執行 DOM 更新。 如果你沒有呼叫該函式,協調演算法會改用函式參照本身、而不是回傳值來比對項目。

我應該怎麼做?

在 @for 區塊中使用 track 函式時,請確認有呼叫它來執行該函式,讓迴圈能為每個項目建立唯一識別。

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

@Component({
  template: `@for (item of items; track trackByName(item)) {}`,
})
class Items {
  protected trackByName(item) {
    return item.name;
  }
}

設定需求

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

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

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

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

詳情請見擴充診斷設定。