ngIf In Angular With Example

*ngIf (Structural Directive )

  • The “IF ELSE”-like condition is the basis on which ngIf operates. We are aware of the overall operation of the if else condition. If the condition in the IF statement is true, the block will be run; if it is false, the block in the ELSE statement will be executed.
  • If you’re using VS Code, hit Ctrl+’ to launch the terminal (you can use any code editor of your choice)
  • By entering the command ng g c ComponentName, a component may be created.
  • To begin, we’ll design a straightforward button that switches between situations.
  1. app.component.html
<button mat-raised-button (click)="getTrue()" color="primary">TRUE</button>
<button mat-raised-button (click)="getFalse()" color="warn">FALSE</button>
  • Two new buttons, TRUE and FALSE, will be added. I’ve used Mat buttons here; to utilise Material buttons, import the Angular MatButtonModule.
  1. MatButtonModule in app.module.ts
import {MatButtonModule} from '@angular/material/button';
  exports: [
  1. app.component.html
<div *ngIf="condition; else falseCondition">
  You have selected: <h2>"True"</h2>
<ng-template #falseCondition>
  You have selected: <h2>"False"</h2>
  1. app.component.ts
condition: boolean;
getTrue() {
    this.condition = true;
getFalse() {
    this.condition = false;
  • ng serve
  1. Output :


Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories