*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.
- 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.
- MatButtonModule in app.module.ts
import {MatButtonModule} from '@angular/material/button'; @NgModule({ exports: [ MatButtonModule, ] })
- app.component.html
<div *ngIf="condition; else falseCondition"> You have selected: <h2>"True"</h2> </div> <ng-template #falseCondition> You have selected: <h2>"False"</h2> </ng-template>
- app.component.ts
condition: boolean; getTrue() { this.condition = true; } getFalse() { this.condition = false; }
- ng serve
- Output :