Учебники

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 и посмотрим на результат.

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>

Если условие истинно, то вызывается шаблон 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, соответствующий шаблон будет отображаться –

Условие действительноНеверный шаблон

Если вы проверите браузер, вы увидите, что вы никогда не получите тег 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>

Если мы удалим условие then , мы получим сообщение «Условие действительно» в браузере, а тег span также доступен в DOM. Например, в app.component.ts мы сделали переменную isavailable равной true.