Angular ngSwtich

Last Updated on May 20, 2022
Angular ngSwtich

Angular ngSwitch

In Angular ngSwitch built-in structural directive also allows us to add or remove the HTML element based on multiple conditions just like a ngIf directive. The ngSwitch directive works just like a switch statement in other programming languages.

Let’s look at code syntax and some code examples of using ngSwitch.

<div [ngSwitch]="switch-expression">
    <p *ngSwitchCase="render if match expresson 1 ">...</p>
    <p *ngSwitchCase="render if match expresson 2">...</p>
    <p *ngSwitchCase=" render if match expresson 3">...</p>
    <p *ngSwitchDefault>render if nothing match from above condtion</p>

Let's take a look at the code example.

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

    selector: 'app-demoComponent',
    template:  `
            <div [ngSwitch]="nRandomNum">
                <p *ngSwitchCase="0"> nRandomNum value is 0</p>
                <p *ngSwitchCase="1"> nRandomNum value is 1</p>
                <p *ngSwitchCase="2"> nRandomNum value is 2</p>
                <p *ngSwitchCase="3"> nRandomNum value is 3</p>
                <p *ngSwitchCase="4"> nRandomNum value is 4</p>
                <p *ngSwitchCase="5"> nRandomNum value is 5</p>
                <p *ngSwitchDefault="1"> nRandomNum value doesn't match between 0 - 5</p>

export class DemoComponent {

    nRandomNum = 10;


As an output, based on the above code we should be able to see the default statement.