Home >>Angular 6 Tutorial >Angular 6 Templates

Angular 6 Templates

Angular 6 Templates

Angular 6 uses the < ng-template > as the Angular 4-like suffix, instead of the < template > used in Angular 2. The explanation Angular 4 has modified < template > to < ng-template > is because the < template > tag and the html < template > style label are in disagreement with the term. It would totally deprecate going ahead.

Now let's use the example along with the condition if anything, and see the performance.

app.component.html


<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"> valid Condition.</span>
   <ng-template #condition1>Condition is valid </ng-template>
   <ng-template #condition2>Condition is invalid </ng-template>
</div>
<button (click) = "myClickFunction($event)">Click Me</button>

We inserted the if declaration with the other condition for the Span tag and will name the condition1 example, then condition2.

The templates are to be called accordingly –

<ng-template #condition1>Condition is valid </ng-template>
<ng-template #condition2>Condition is invalid</ng-template>

If the condition is true, then the condition1 template is called, otherwise 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 6 Project!';
   //array of months.
   months = ["Jan", "Feb", "Mar", "Apr",
      "May", "June", "Jul", "Aug", "Sep",
      "Oct", "Nov", "Dec"];
   isavailable = false;
   myClickFunction(event) {
      this.isavailable = false;
   }
   changemonths(event) {
      alert("Changed month from the Dropdown");
      console.log(event);
   }
}


When you check the browser, you can find the dom has no span tag. This has the state in the dom template that is null.

The next line of code in html will help us get the dom span tag.


<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 </ng-template>
   <ng-template #condition2>Condition is invalid</ng-template>
</div>
<button (click)="myClickFunction($event)">Click Me</button>

If we disable the condition then we get the notification "Condition is true" in the browser and the span tag is still visible in the dom. For illustration we have rendered the isavailable variable valid in app.component.ts.


No Sidebar ads