擴充診斷

缺少控制流程指令

這項診斷會確保:在範本中使用已知控制流程指令(例如 *ngIf、*ngFor、*ngSwitchCase 或 *ngSwitchDefault)的獨立元件,也確實匯入了這些指令,無論是逐一匯入,還是透過匯入 CommonModule 來取得。

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

@Component({
  // Template uses `*ngIf`, but no corresponding directive imported.
  imports: [],
  template: `<div *ngIf="visible">Hi</div>`,
})
class MyComponent {}

這樣寫有什麼問題?

使用控制流程指令卻沒有匯入它,會在執行階段失敗,因為 Angular 會嘗試繫結到 HTML 元素的 ngIf 屬性,而該屬性並不存在。

我應該怎麼做?

請確認有匯入對應的控制流程指令。

指令可以逐一匯入:

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

@Component({
  imports: [NgIf],
  template: `<div *ngIf="visible">Hi</div>`,
})
class MyComponent {}

或者也可以匯入完整的 CommonModule,它包含所有控制流程指令:

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

@Component({
  imports: [CommonModule],
  template: `<div *ngIf="visible">Hi</div>`,
})
class MyComponent {}

設定需求

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

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

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

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

詳情請見擴充診斷設定。