In this tutorial we will learn to use angular if else, ngIf, ngif else and elseif. if else is used to make conditional statement in template same as we can also use if else. As we all programmers know if or if else condition is used to create conditional statements so in angular template we can also use the if else
but for elseif
there is no direct way but we can use alternate way.
ngIf is a structural directive which is used to control the layout of dom by adding and removing the content of dom. You can read more about structural directive here What is directives and types of directive in angular?
Syntax of angular if else
Here is the syntax of *ngIf
<ng-container *ngIf="count == 1"></ng-container>
Syntax of *ngIf
else
<ng-container *ngIf="count === 1;else second"></ng-container>
<ng-template #second>
<ng-container *ngIf="count === 2"></ng-container>
</ng-template>
Syntax of *ngIf
elseif
<ng-container *ngIf="count === 1;else second"></ng-container>
<ng-template #second>
<ng-container *ngIf="count === 2;else third"></ng-container>
</ng-template>
<ng-template #third></ng-template>
You can also achieve the same as below
<ng-container *ngIf="count === 1;"></ng-container>
<ng-container *ngIf="count === 2"></ng-container>
<ng-container *ngIf="count<0"></ng-container>
Let’s understand use NgIf, if else and elseif with example
Step 1 : Create an angular app
First step is to setup an angular app using below command
ng new example-component
Step 2: Create a Component
Create a component so we can add conditional statements
ng g c test-condition
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-test-condition',
templateUrl: './test-condition.component.html',
styleUrls: ['./test-condition.component.css']
})
export class TestConditionComponent implements OnInit {
count:number =1;
constructor() {
setInterval(()=>{
this.count++;
},2000)
}
}
Step 3 : Create template and add conditional *ngIf
Now, add simple html template with *ngif
<h1>use NgIf if else and elseif in angular- ReaderStacks</h1>
<h2>Example 1</h2>
<ng-container *ngIf="count === 1;else second"> Condition 1 </ng-container>
<ng-template #second>
<ng-container *ngIf="count === 2;else third" >Condition 2 </ng-container>
</ng-template>
<ng-template #third> Condition 3</ng-template>
<h2>Example 2</h2>
<!-- count = 5 -->
<ng-container *ngIf="count >= 1 && count <= 3; then elseif3"></ng-container>
<ng-container *ngIf="count >= 4 && count <= 6; then elseif4"></ng-container>
<ng-container *ngIf="count >= 7; then elseif5"></ng-container>
<!-- If Statement -->
<ng-template #elseif3>
count between 1 and 3
</ng-template>
<!-- If Else Statement -->
<ng-template #elseif4>
count between 4 and 6
</ng-template>
<!-- Else Statement -->
<ng-template #elseif5>
count greater than 7
</ng-template>
Live Example and code:
Stack blitz : https://stackblitz.com/edit/angular-ivy-jrvtth