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
广告