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

By Hardik Savani August 5, 2024 Category : Angular

Today, I would like to show you angular 18 @if example. you will learn angular 18 @if else example. If you have a question about angular 18 conditional statements example then I will give a simple example with a solution. let’s discuss about angular 18 if statement example.

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

Let's see the simple example code:

Example 1: Angular 18 @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 18 @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
  
</div>

Output:

You will see the following output:

Two

I hope it can help you...

Shares