Angular 4 - 模板



Angular 4 使用 <ng-template> 作為標籤,而不是 Angular 2 中使用的 <template>。Angular 4 將 <template> 更改為 <ng-template> 的原因是 <template> 標籤與 HTML 標準標籤 <template> 之間存在命名衝突。未來它將完全棄用。這是 Angular 4 的主要變化之一。

現在讓我們結合if else 條件使用模板,並檢視輸出。

app.component.html

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select (change) = "changemonths($event)" name = "month">
      <option *ngFor = "let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf = "isavailable;then condition1 else condition2">Condition is valid.</span>
   <ng-template #condition1>Condition is valid from template</ng-template>
   <ng-template #condition2>Condition is invalid from template</ng-template>
</div>
<button (click) = "myClickFunction($event)">Click Me</button>

對於 Span 標籤,我們添加了帶有else 條件的if 語句,並將呼叫模板 condition1,否則呼叫 condition2。

模板的呼叫方式如下:

<ng-template #condition1>Condition is valid from template</ng-template>
<ng-template #condition2>Condition is invalid from template</ng-template>

如果條件為真,則呼叫 condition1 模板,否則呼叫 condition2。

app.component.ts

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

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "February", "March", "April",
            "May", "June", "July", "August", "September",
            "October", "November", "December"];
   isavailable = false;
   myClickFunction(event) {
      this.isavailable = false;
   }
   changemonths(event) {
      alert("Changed month from the Dropdown");
      console.log(event);
   }
}

瀏覽器中的輸出如下:

App Component.ts Output

變數isavailable 為 false,因此列印 condition2 模板。如果單擊按鈕,則將呼叫相應的模板。如果您檢查瀏覽器,您會看到 DOM 中從未出現 span 標籤。以下示例將幫助您理解這一點。

Inspect The Browser

如果您檢查瀏覽器,您會看到 DOM 中沒有 span 標籤。DOM 中只有Condition is invalid from template

HTML 中的以下程式碼行將幫助我們在 DOM 中獲取 span 標籤。

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select (change) = "changemonths($event)" name = "month">
      <option *ngFor = "let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf = "isavailable; else condition2">Condition is valid.</span>
   <ng-template #condition1>Condition is valid from template</ng-template>
   <ng-template #condition2>Condition is invalid from template</ng-template>
</div>

<button (click)="myClickFunction($event)">Click Me</button>

如果我們刪除 then 條件,我們將在瀏覽器中得到“Condition is valid” 訊息,並且 span 標籤也出現在 DOM 中。例如,在app.component.ts 中,我們將isavailable 變數設定為 true。

app.component.ts isavailable
廣告