填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

NgIf

本結構型指令用於根據表示式的值(強轉為 boolean)是否為真值,來有條件的包含某個範本。當表示式計算為 true 時,Angular 會渲染 then 子句中提供的範本,當為 false 或 null 時則渲染可選的 else 子句中的範本。else 子句的預設範本是空白範本。

A structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. When the expression evaluates to true, Angular renders the template provided in a then clause, and when false or null, Angular renders the template provided in an optional else clause. The default template for the else clause is blank.

檢視"說明"...

Exported from

選擇器

屬性

屬性說明
@Input()
ngIf: T
只寫

布林表示式,將其作為顯示範本的條件進行計算。

The Boolean expression to evaluate as the condition for showing a template.

@Input()
ngIfThen: TemplateRef<NgIfContext<T>>
只寫

當此條件表示式計算為 true 時要顯示的範本。

A template to show if the condition expression evaluates to true.

@Input()
ngIfElse: TemplateRef<NgIfContext<T>>
只寫

當此條件表示式計算為 false 時要顯示的範本。

A template to show if the condition expression evaluates to false.

說明

通常使用指令的簡寫形式 *ngIf="condition",作為插入範本的錨點元素的屬性提供。Angular 將其擴充套件為更明確的版本,其中錨點元素包含在 <ng-template> 元素中。

A shorthand form of the directive, *ngIf="condition", is generally used, provided as an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element.

具有簡寫語法的簡單形式:

Simple form with shorthand syntax:

      
      <div *ngIf="condition">Content to render when condition is true.</div>
    

具有擴充套件語法的簡單形式:

Simple form with expanded syntax:

      
      <ng-template [ngIf]="condition"><div>Content to render when condition is
true.</div></ng-template>
    

帶有 “else” 塊的格式:

Form with an "else" block:

      
      <div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>
    

帶 “then” 和 “else” 塊的簡寫形式:

Shorthand form with "then" and "else" blocks:

      
      <div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>Content to render when condition is true.</ng-template>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>
    

本地儲存值的形式:

Form with storing the value locally:

      
      <div *ngIf="condition as value; else elseBlock">{{value}}</div>
<ng-template #elseBlock>Content to render when value is null.</ng-template>
    

*ngIf 指令通常用於根據條件顯示內聯範本,就像下面的例子展示的一樣。預設的 else 範本是空白的。

The *ngIf directive is most commonly used to conditionally show an inline template, as seen in the following example. The default else template is blank.

      
      @Component({
  selector: 'ng-if-simple',
  template: `
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
    show = {{show}}
    <br>
    <div *ngIf="show">Text to show</div>
`
})
export class NgIfSimple {
  show = true;
}
    

使用 else 顯示替代範本

Showing an alternative template using else

要在 expression 計算為 false 時顯示一個範本,請使用如下所示的 else 範本繫結。else 繫結指向一個帶有 #elseBlock 標籤的 <ng-template>。該範本可以定義在元件檢視中的任何地方,但通常放在 ngIf 的緊後方,以提高可讀性。

To display a template when expression evaluates to false, use an else template binding as shown in the following example. The else binding points to an <ng-template> element labeled #elseBlock. The template can be defined anywhere in the component view, but is typically placed right after ngIf for readability.

      
      @Component({
  selector: 'ng-if-else',
  template: `
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
    show = {{show}}
    <br>
    <div *ngIf="show; else elseBlock">Text to show</div>
    <ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
`
})
export class NgIfElse {
  show = true;
}
    

使用內部 then 範本

Using an external then template

在前面的例子中,then 子句的範本是內聯的,也就是作為 ngIf 指令所在標籤的內容。你還可以透過參考一個帶標籤的 <ng-template> 元素來指定一個在外部定義的範本。這樣就可以讓你在執行時更改範本,就像下面的例子所示範的。

In the previous example, the then-clause template is specified inline, as the content of the tag that contains the ngIf directive. You can also specify a template that is defined externally, by referencing a labeled <ng-template> element. When you do this, you can change which template to use at runtime, as shown in the following example.

      
      @Component({
  selector: 'ng-if-then-else',
  template: `
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
    <button (click)="switchPrimary()">Switch Primary</button>
    show = {{show}}
    <br>
    <div *ngIf="show; then thenBlock; else elseBlock">this is ignored</div>
    <ng-template #primaryBlock>Primary text to show</ng-template>
    <ng-template #secondaryBlock>Secondary text to show</ng-template>
    <ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
`
})
export class NgIfThenElse implements OnInit {
  thenBlock: TemplateRef<any>|null = null;
  show = true;

  @ViewChild('primaryBlock', {static: true}) primaryBlock: TemplateRef<any>|null = null;
  @ViewChild('secondaryBlock', {static: true}) secondaryBlock: TemplateRef<any>|null = null;

  switchPrimary() {
    this.thenBlock = this.thenBlock === this.primaryBlock ? this.secondaryBlock : this.primaryBlock;
  }

  ngOnInit() {
    this.thenBlock = this.primaryBlock;
  }
}
    

把條件結果儲存在變數中

Storing a conditional result in a variable

比如你想顯示同一個物件中的一組屬性。如果你在等待非同步資料,此物件可能是未定義的。這時候,你可以使用 ngIf,並且把此條件結果儲存在一個區域性變數中,如下例所示。

You might want to show a set of properties from the same object. If you are waiting for asynchronous data, the object can be undefined. In this case, you can use ngIf and store the result of the condition in a local variable as shown in the following example.

      
      @Component({
  selector: 'ng-if-as',
  template: `
    <button (click)="nextUser()">Next User</button>
    <br>
    <div *ngIf="userObservable | async as user; else loading">
      Hello {{user.last}}, {{user.first}}!
    </div>
    <ng-template #loading let-user>Waiting... (user is {{user|json}})</ng-template>
`
})
export class NgIfAs {
  userObservable = new Subject<{first: string, last: string}>();
  first = ['John', 'Mike', 'Mary', 'Bob'];
  firstIndex = 0;
  last = ['Smith', 'Novotny', 'Angular'];
  lastIndex = 0;

  nextUser() {
    let first = this.first[this.firstIndex++];
    if (this.firstIndex >= this.first.length) this.firstIndex = 0;
    let last = this.last[this.lastIndex++];
    if (this.lastIndex >= this.last.length) this.lastIndex = 0;
    this.userObservable.next({first, last});
  }
}
    

這段程式碼只使用了一個 AsyncPipe,所以只會建立一個訂閱。此條件表示式把 userStream|async 的結果儲存在區域性變數 user 中。然後你就可以反覆繫結這個區域性變數 user 了。

This code uses only one AsyncPipe, so only one subscription is created. The conditional statement stores the result of userStream|async in the local variable user. You can then bind the local user repeatedly.

只有當 userStream 返回了值的時候,才會有條件的顯示此資料。所以你不用使用安全導航運算子 (?.) 來在訪問屬性時避免空值。你可以在等待資料時顯示一個備用範本。

The conditional displays the data only if userStream returns a value, so you don't need to use the safe-navigation-operator (?.) to guard against null values when accessing properties. You can display an alternative template while waiting for the data.

簡寫語法

Shorthand syntax

*ngIf 的簡寫語法會把 "then" 和 "else" 子句分別擴充套件成兩個獨立的範本。比如,考慮下列簡寫語句,它要在等待資料載入期間顯示一個載入中頁面。

The shorthand syntax *ngIf expands into two separate template specifications for the "then" and "else" clauses. For example, consider the following shorthand statement, that is meant to show a loading page while waiting for data to be loaded.

      
      <div class="hero-list" *ngIf="heroes else loading">
 ...
</div>

<ng-template #loading>
 <div>Loading...</div>
</ng-template>
    

你可以看到,"else" 子句參考了帶有 #loading 標籤的 <ng-template>,而 "then" 子句的範本是作為宿主元素的內容提供的。

You can see that the "else" clause references the <ng-template> with the #loading label, and the template for the "then" clause is provided as the content of the anchor element.

不過,當 Angular 擴充套件此簡寫語法的時候,它建立了另一個帶有 ngIfngIfElse 指令的 <ng-template>。此宿主元素包含的 "then" 子句的範本變成了無標籤的 <ng-template> 的內容。

However, when Angular expands the shorthand syntax, it creates another <ng-template> tag, with ngIf and ngIfElse directives. The anchor element containing the template for the "then" clause becomes the content of this unlabeled <ng-template> tag.

      
      <ng-template [ngIf]="heroes" [ngIfElse]="loading">
 <div class="hero-list">
  ...
 </div>
</ng-template>

<ng-template #loading>
 <div>Loading...</div>
</ng-template>
    

隱式範本物件的存在,影響了結構型指令的巢狀規則。欲知詳情,參見結構型指令

The presence of the implicit template object has implications for the nesting of structural directives. For more on this subject, see Structural Directives.

靜態屬性

屬性說明
static ngTemplateGuard_ngIf: 'binding'

為繫結到 ngIf 輸入屬性上的範本確保正確的型別。

Assert the correct type of the expression bound to the ngIf input within the template.

該靜態欄位的存在向 Ivy 範本型別檢查編譯器發出訊號,即當 NgIf 結構化指令渲染其範本時,應以某種方式窄化 ngIf。對於 NgIf,繫結表示式本身用於窄化其型別,這允許 TypeScript 的 strictNullChecks 功能與 NgIf 一起使用。

The presence of this static field is a signal to the Ivy template type check compiler that when the NgIf structural directive renders its template, the type of the expression bound to ngIf should be narrowed in some way. For NgIf, the binding expression itself is used to narrow its type, which allows the strictNullChecks feature of TypeScript to work with NgIf.

靜態方法

NgIf 將要渲染的範本確保正確的上下文型別。

Asserts the correct type of the context for the template that NgIf will render.

      
      static ngTemplateContextGuard<T>(dir: NgIf<T>, ctx: any): ctx is NgIfContext<Exclude<T, false | 0 | '' | null | undefined>>
    
引數
dir NgIf
ctx any
返回值

ctx is NgIfContext<Exclude<T, false | 0 | '' | null | undefined>>

該方法用於向 Ivy 範本型別檢查編譯器發出訊號,即 NgIf 結構化指令會使用特定的上下文型別渲染其範本。

The presence of this method is a signal to the Ivy template type-check compiler that the NgIf structural directive renders its template with a specific context type.