Angular 17 Conditional Statements @if, @else if, and @else Example

By Hardik Savani January 19, 2024 Category : Angular

Hey Artisan,

This definitive guide, we will show you angular 17 @if example. if you want to see an example of angular 17 @if else example then you are in the right place. I explained simply about angular 17 conditional statements example. This article will give you a simple example of angular 17 if statement example. Alright, let’s dive into the steps.

Angular provides conditional statements using ngIf, ifBlock, and elseBlock but, Angular 17 changed the condition statement flow with new syntax. You can use @if, @else, and @else if for the if condition in angular 17. You can see one be one example with output and a new conditional statement.

Let's see the simple example code:

Example 1: Angular 17 @if and @else Statement

You can update the following code with the app.component.ts file:

src/app/app.component.ts

import { Component } from '@angular/core';

import { CommonModule } from '@angular/common';

@Component({

selector: 'app-root',

standalone: true,

imports: [CommonModule],

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent {

type:number = 2;

}

Here, update the app.component.html file:

src/app/app.component.html

<div class="container">

<!-- Using @if with @else -->

@if (type == 1) {

<h2>One</h2>

} @else {

<h2>Two</h2>

}

<!-- Using ngIf with else -->

<h2 *ngIf="type == 1; else elseBlock">One</h2>

<ng-template #elseBlock><h2>Two</h2></ng-template>

</div>

Output:

You will see the following output:

Two

Example 2: Angular 17 @if, @else if and @else Statement

You can update the following code with the app.component.ts file:

src/app/app.component.ts

import { Component } from '@angular/core';

import { CommonModule } from '@angular/common';

@Component({

selector: 'app-root',

standalone: true,

imports: [CommonModule],

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent {

type:number = 2;

}

Here, update the app.component.html file:

src/app/app.component.html

<div class="container">

<!-- Using @if with @else if -->

@if (type == 1) {

<h2>One</h2>

} @else if(type == 2) {

<h2>Two</h2>

} @else {

<h2>Three</h2>

}

<!-- Using ngIf with else if -->

<h2 *ngIf="type == 1; else ifBlock">One</h2>

<ng-template #ifBlock><h2 *ngIf="type == 2">Two</h2></ng-template>

<h2 *ngIf="type != 1 && type != 2">Three</h2>

</div>

Output:

You will see the following output:

Two

I hope it can help you...

Shares