📅  最后修改于: 2020-10-27 02:30:31             🧑  作者: Mango
Angular 7使用
现在让我们将模板与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,else condition2。
模板被称为如下-
Condition is valid from template
Condition is invalid from template
如果条件为true,则将调用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 7';
// declared array of months.
months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
isavailable = false; // variable is set to true
myClickFunction(event) {
//just added console.log which will display the event details in browser on click of the button.
alert("Button is clicked");
console.log(event);
}
changemonths(event) {
alert("Changed month from the Dropdown");
}
}
浏览器中的输出如下-
变量isavailable为false,因此会打印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 7';
// declared array of months.
months = ["January", "Feburary", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
isavailable = false; //variable is set to true
myClickFunction(event) {
this.isavailable = !this.isavailable;
// variable is toggled onclick of the button
}
changemonths(event) {
alert("Changed month from the Dropdown");
}
}
单击按钮可切换isavailable变量,如下所示-
myClickFunction(event) {
this.isavailable = !this.isavailable;
}
当您基于isavailable变量的值单击按钮时,将显示相应的模板-
如果您检查浏览器,将会看到您在dom中永远不会获得span标签。以下示例将帮助您理解相同的内容。
尽管在app.component.html中,我们为以下条件添加了span标签和
Condition is valid.
Condition is valid from template
Condition is invalid from template
在浏览器中检查span标签以及dom结构中的
html中的以下代码行将帮助我们在dom中获取span标签-
Welcome to {{title}}.
Months :
Condition is valid.
Condition is valid from template
Condition is invalid from template
如果我们去掉then条件下,我们得到的“条件有效”的消息在浏览器和跨标签也可在DOM。例如,在app.component.ts,我们已经取得了isavailable变量为真。