模板
优质
小牛编辑
130浏览
2023-12-01
Angular 4使用《ng-template》作为标签,而不是Angular2中使用的《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);
}
}
浏览器中的输出如下 -

变量isavailable为false,因此打印出condition2模板。 如果单击该按钮,将调用相应的模板。 如果您检查浏览器,您将看到永远不会在dom中获得span标记。 以下示例将帮助您理解相同的内容。

如果您检查浏览器,您将看到dom没有span标记。 它具有Condition is invalid from template在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”消息,并且dom中也可以使用span标记。 例如,在app.component.ts ,我们将app.component.ts变量设为true。
