ngIf @if in Angular
Written By: Avinash Malhotra
Updated on
ngIf
NgIf directive is used to print element if condition is true. It will add element and its descendants in DOM only if it is true. The syntax id *ngIf.
When NgIf is false, Angular will remove the element and its descendants from the DOM. This will free up memory and boost speed of application.
The asterisk * prefix is used in NgIf and NgFor to tell Angular to interpret and convert it into a longer form.
To use *ngIf, import CommonModule in angular app first and
Car is hybrid
<!-- app.component.ts -->
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
imports: [CommonModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
hybrid=true;
nonhybrid=false;
}
<!-- app.component.html -->
<p *ngIf="hybrid">Car is hybrid</p>
<p *ngIf="nonhybrid">Car is not hybrid</p>
using not in ngIf
Car is not hybrid
<!-- app.component.ts -->
export class AppComponent {
hybrid=true;
nonhybrid=false;
}
<!-- app.component.html -->
<p *ngIf="!hybrid">Car is hybrid</p>
<p *ngIf="!nonhybrid">Car is not hybrid</p>
NgIf will not set display none if its false. It will remove elements from DOM. This will free up memory and boost code performance.
@if
@if is introduced in Angular 17 instead of ngIf. Its same like JavaScript If. It can be directly used in template.
Unlike, ngIf, @if does not require CommonModule to import first and then use.
@if example
Valid
<!-- app.component.ts -->
export class AppComponent {
valid=true;
}
<!-- app.component.html -->
@if(valid){ <p>Valid</p> }
@else example
@else is used for else block after @if.
Invalid
<!-- app.component.ts -->
export class AppComponent {
valid=false;
}
<!-- app.component.html -->
@if(valid){ <p>Valid</p> }
@else{ <p>Invalid</p> }
@else if
@else if is used for else if block after @if.
Invalid
<!-- app.component.ts -->
export class AppComponent {
num=0;
}
<!-- app.component.html -->
@if(num==0){ <p>Zero</p> }
@else if(num>0){ <p>Positive</p> }
@else if(num<0){ <p>Negative</p> }
@else{ <p>Not a number</p> }
with null
ngIf with null will prevent element from displaying to user. This means, the element is not available in DOM.
Car is not hybrid
<!-- app.component.ts -->
export class AppComponent {
hybrid=null;
}
<!-- app.component.html -->
<p *ngIf="hybrid">Car is hybrid</p>
<p *ngIf="!hybrid">Car is not hybrid</p>