Angular Templates
- Templates are available from Angular 2 as <template>
- It got changed as <ng-template> from angular 4
Lets see how we can use it with if-else condition.
We can use if else using *ngIf as below. We have used ngIf with a span tag. It will call the template display 1 and display 2 based on the value isSelected.
<span *ngIf="isSelected; then display1 else display2"> </span> <ng-template #display1>Thank you for choosing this option</ng-template> <ng-template #display2>Please choose any option</ng-template>
Values of isSelected are declared in app.component.ts file and the onchange function will change its value when the value is selected in drop down.
isSelected = false; myonChange(e){ this.isSelected = true; }
Below screenshot will show the output of this screen.
Below screenshot show the output on the browser. After choosing the value in drop down.
We can see the caption has changed.
So the app.component.html will look like below
<div class="toolbar" role="banner"> <img width="40" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==" /> <span>Welcome to {{ title }}</span> <br> </div> <div class="content"> <button (click) = "myfun($event)"> Click Me </button> <br> <select (change) = "myonChange($event)"> <option>select</option> <option>hello</option> <option>world</option> </select> <span *ngIf="isSelected; then display1 else display2"> </span> <ng-template #display1><h1>Thank you for choosing this option</h1></ng-template> <ng-template #display2><h1>Please choose any option</h1></ng-template> </div>
App.component.ts will look like below.
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'myfirstapp'; isSelected = false; myfun(event){ alert(event); } myonChange(e){ this.isSelected = true; } }