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.
Car is 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>
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.
@if example
Valid
<!-- app.component.ts -->
export class AppComponent {
valid=true;
}
<!-- app.component.html -->
@if(valid){ <p>Valid</p> }
@if and @else example
Invalid
<!-- app.component.ts -->
export class AppComponent {
valid=false;
}
<!-- app.component.html -->
@if(valid){ <p>Valid</p> }
@else{ <p>Invalid</p> }
@if, @else if and @else
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>