ngIf with an else Condition

  • 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>

Add the following code in app.component.ts file

import { Component } from '@angular/core';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'ngIfElseDemo';
  isButtonClicked = false;
      this.isButtonClicked = false;
      this.isButtonClicked = true;

Output looks like below :

Leave a Comment