Welcome folks today in this blog post we will be looking how to use the ng-template
directive in angular 14
to show & hide dynamic messages using the ngIf and else
statements in typescript in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular
project using the below command as shown below
ng new sampleproject
cd sampleproject
And after that you will see the below directory
structure of the angular app as shown below
And now we need to go to app.component.html
file and copy paste the below html code where we have the span
tag where we have the ngIf and else
statements for the boolean variable. And based upon the value of the variable we are showing the two
templates. And the template is constructed with the help of ng-template
directive and also we have attached the reference to each of the template. And then we have the simple button
to toggle the template
on button click as shown below.
app.component.html
1 2 3 4 5 6 7 8 |
<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> |
And now we need to copy paste the below code inside the app.component.ts
file as shown below
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { isavailable = false; // variable is set to true myClickFunction(event: any) { //just added console.log which will display the event details in browser on click of the button. if (this.isavailable) { this.isavailable = false; } else { this.isavailable = true; } } } |
As you can see in the above typescript
code we have the boolean variable declared and inside the function we are toggling the value
of the variable comparing the value inside the if condition. And now if you press the button the template message
will change because the variable value will change from true to false and vice versa.