Open In App

Angular10 NgSwitch Directive

Last Updated : 21 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see what is NgSwitch in Angular 10 and how to use it.

The NgSwitch in Angular10 is used to specify the condition to show or hide the child elements.

Syntax:

<li *NgSwitch='condition'></li>

NgModule: Module used by NgSwitch is:

  • CommonModule

 

Selectors:

  • [NgSwitch]
    Directives:

  • NgSwitchCase

Approach: 

  • Create the angular app to be used
  • There is no need for any import for the NgSwitch to be used
  • define a variable in app.component.ts
  • in app.component.html use NgSwitch with NgSwitchCase directive in the element with conditions to be checked
  • Serve the angular app using ng serve to see the output

Example:

app.component.ts




import { Component, Inject } 
from '@angular/core';
import { PLATFORM_ID } 
from '@angular/core';
import { isPlatformWorkerApp } 
from '@angular/common';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  num = 2;
}


app.component.html




<div [ngSwitch]="num">
  <div *ngSwitchCase="'1'">One</div>
  <div *ngSwitchCase="'2'">Two</div>
  <div *ngSwitchCase="'3'">Three</div>
  <div *ngSwitchCase="'4'">Four</div>
  <div *ngSwitchCase="'5'">Five</div>
</div>


Output:

Reference: https://angular.io/api/common/NgSwitch



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads