What Is ngSwitch In Angular

Hello Friends, In this article, we will learn how to use ngSwitch in the Angular application.

1. ngSwitch directive is applied to the container element with the switch expression. The ngSwitch is used to Add or Remove DOM Element. It is same as switch statement of C#.

2. ngSwitchCase directive is used to check the inner elements with a match expression. if the switch expression value is match  that mean’s  the inner element is added to the DOM. And other inner elements are removed from the DOM. If more than one match, then matching elements are added to the DOM.

3. ngSwitchDefault  directive is used when no match is found. and you can add more than one ngSwitchDeafault directives and also displayed it.


Step 1 : Now let’s create a new Angular application using the below  command.

ng new ngSwitchDemo --routing

Step 2 : Add below code in app.module.ts

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Step 3 : Add below code in app.component.ts

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

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'ngSwitchDemo';

Step 4 : Add below code in app.component.html

<h1>Enter Month No :  <input type='text' [(ngModel)] ="Month"/></h1>
<div [ngSwitch]="Month">
    <div *ngSwitchCase='1'><h1>January</h1></div>
    <div *ngSwitchCase='2'><h1>February</h1></div>
    <div *ngSwitchCase='3'><h1>March</h1></div>
    <div *ngSwitchCase='4'><h1>April</h1></div>
    <div *ngSwitchCase='5'><h1>May</h1></div>
    <div *ngSwitchCase='6'><h1>June</h1></div>
    <div *ngSwitchCase='7'><h1>July</h1></div>
    <div *ngSwitchCase='8'><h1>August</h1></div>
    <div *ngSwitchCase='9'><h1>September</h1></div>
    <div *ngSwitchCase='10'><h1>October</h1></div>
    <div *ngSwitchCase='11'><h1>November</h1></div>
    <div *ngSwitchCase='12'><h1>December</h1></div>
    <div *ngSwitchDefault><h1>Please Enter Valid Month No..</h1></div>


Let’s See Output


Also check How To Upload Images Using Cloud nary In ASP.Net MVC

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories