- ngIF is a Structural directive and else part is just an add on to it.
- This means it changes the structure of the dom using it hence its always represented with a * (start) ahead of it
- Lets create a new Angular project using Angular CLI for this example
- Add the following code in app.component.html file
<H1>Hello User</H1> <button (click)="onButtonClick()">Toggle Me</button> <p *ngIf="isButtonClicked; else noButtonClicked">The button is clicked</p> <ng-template #noButtonClicked> <p>The button is not clicked</p> </ng-template>
Add the following code in app.component.ts file
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'ngIfElseDemo'; isButtonClicked = false; onButtonClick(){ if(this.isButtonClicked){ this.isButtonClicked = false; }else{ this.isButtonClicked = true; } } }
Output looks like below :