*ngIf directive:
-----------------
This is used to show[add]|hide[remove] html element [ from browser DOM]
Syntax:
1. <tagname *ngIf="cond"> --> if(cond)
... { ... }
</tagname>
2. <tagname *ngIf="cond;then template1 else template2"> --> if(cond)
</tagname> { .. }
else
{...}
The basic syntax of the ngIf directive is very simple, all we need to do is prefix the directive name with an asterisk (*)
Example
.html changes
<div *ngIf="isValid"><b>The Data is valid.</b></div><div *ngIf="!isValid"><b>The Data is invalid.</b></div>.ts Changesimport { Component } from '@angular/core';@Component({selector: 'app-ngswitchdemo',templateUrl: './ngswitchdemo.component.html',styleUrls: ['./ngswitchdemo.component.css']})export class NgswitchdemoComponent {isValid:boolean=true;}
Output
Example 2
.html
<div><input type="radio" name="rb" (click)= "ChangeData(true)" checked > Valid<input type="radio" name="rb" (click)= "ChangeData(false)"> Invalid</div><div *ngIf="isValid"><b>The Data is valid.</b></div><div *ngIf="!isValid"><b>The Data is invalid.</b></div>.tsNgIf directive with else block
Here, we need to use ngTemplate for else BlockSyntax:<div *ngIf = “condition; else elseBlock”>…</div> <ng-template #elseblock>….</ng-template>.html<div><input type="radio" name="rb" (click)= "ChangeData(true)" checked > Valid<input type="radio" name="rb" (click)= "ChangeData(false)"> Invalid</div><div *ngIf="isValid else elseblock"><b>The Data is valid.</b></div><ng-template #elseblock><div ><b>The Data is invalid.</b></div></ng-template>.ts changesisValid: boolean = true;ChangeData(valid: boolean) {this.isValid = valid;}OutputExample 3.html<div style="font-size:x-large;margin:10px">enter number:<input type="number" [(ngModel)]="n"> <br><span *ngIf="n%2==0;then template1 else template2"></span><ng-template #template1>even</ng-template><ng-template #template2>odd</ng-template></div><hr><button (click)="toggle()">{{flag?'hide':'show'}} prod info</button><div style="font-size:x-large;border:5px solid black;margin:10px;width:30%" *ngIf="flag">productid:p001 <br>name :aiwa tv <br>pic :<br><img src="./assets/aiwa.jpg" height="200" width="200"></div>.ts changes