Angular7 - шаблоны
Angular 7 использует <ng-template> в качестве тега вместо <template>, который используется в Angular2. <ng-template> используется с момента выпуска Angular 4, а более ранняя версия, то есть Angular 2, использует <template> для той же цели. Причина, по которой он начал использовать <ng-template> вместо <template> начиная с Angular 4, заключается в том, что существует конфликт имен между тегом <template> и стандартным тегом html <template>. Он полностью устареет в будущем. Это было одно из основных изменений, внесенных в версию Angular 4.
Давайте теперь использовать шаблон вместе с if else condition и посмотрим на результат.
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 condition и вызовет шаблон condition1, else 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 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ложно, поэтому печатается шаблон 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 переменной будет отображаться соответствующий шаблон -


Если вы проверите браузер, вы увидите, что вы никогда не получите тег span в dom. Следующий пример поможет вам понять то же самое.

Хотя в app.component.html мы добавили тег span и <ng-template> для условия, как показано ниже -
<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>
Мы не видим тег span, а также <ng-template> в структуре dom, когда проверяем то же самое в браузере.
Следующая строка кода в html поможет нам получить тег span в dom -
<!--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>
Если мы удалим thencondition, мы получаем сообщение «Condition is valid» в браузере, и тег span также доступен в dom. Например, вapp.component.ts, мы сделали isavailable переменная как истина.
