Angular 4 使用< ng-template> 作为标签,而不是Angular2中使用的< template> . Angular 4将< template> 更改为< ng-template> 的原因是因为< template> 之间存在名称冲突标签和html < template> 标准标签.它将完全弃用.这是Angular 4中的一个主要变化.
现在让我们使用模板和 if else 条件并查看输出.
app.component.html
Welcome to {{title}}.
Months :Condition is valid.Condition is valid from template Condition is invalid from template
对于Span标记,我们添加了带 else 条件的 if 语句并将调用模板condition1,否则condition2.
模板的调用如下 :
Condition is valid from template Condition is invalid from 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标记.它具有dom中条件无效的模板.
html中的以下代码行将帮助我们在dom中获取span标记.
Welcome to {{title}}.
Months :Condition is valid.Condition is valid from template Condition is invalid from template
如果我们删除then条件,我们在浏览器中得到"条件有效"消息,并且span标记也是在dom中可用.例如,在 app.component.ts 中,我们将 isavailable 变量设为true.