Angular 4 模板
Angular 4
uses the
现在让我们将模板与 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 标签,我们添加了 if 与声明 else 条件并将调用模板条件1,否则调用条件2。
模板调用如下:
<ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template>
如果条件为真,则调用条件1 模板,否则调用条件2。
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!'; // 月份数组。 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); } }
浏览器中的输出如下:
变量 可用 为假,因此打印条件 2 模板。如果单击该按钮,将调用相应的模板。如果你检查浏览器,你会发现你永远不会在 dom 中获得 span 标签。以下示例将帮助你理解相同的内容。
如果你检查浏览器,你会看到 dom 没有 span 标签。它有 模板中的条件无效 在dom。
以下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 条件,我们得到 “条件有效” 浏览器中的 message 和 span 标签在 dom 中也可用。例如,在 app.component.ts , 我们做了 可用 变量为真。