Welcome Guest! (App Version 3.1)

websitnero logo name

[ngSwitch]

Usage of ngSwitch

ngSwitch is an attribute directive but not used alone. It is used with 2 of the structural directives -- ngSwitchCase and ngSwitchDefault. Along, these 3 make the implementation of switch-case in Angular.

Practical Examples of [ngSwitch]

Please follow the mentioned steps:

  1. Create a compennt named 'home'
  2. Add the home component in the app.component.html file removing all boilerplate code there.
  3. Add the [ngSwitch] along with *ngSwitchCase and *ngSwitchDefault (1 Attribute directive and 2 Structural Directives) together to implement Switch-Case concept in Angular along with a default value.

home.component.html


<div *ngFor="let x of students" [ngSwitch]="x.country">

    <p style="background:blue;" *ngSwitchCase="'USA'">{{x.name}}, {{x.country}}</p>
    <p style="background:red;" *ngSwitchCase="'UK'">{{x.name}}, {{x.country}}</p>
    <p style="background:gray" *ngSwitchDefault>{{x.name}}, {{x.country}}</p>

</div>

home.component.ts

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  students = [
    {name: 'Peter', country: 'USA'},
    {name: 'Lily', country: 'UK'},
    {name: 'Albert',  country: 'China'},
    {name: 'Rosy', country: 'USA'},
    {name: 'Siliva',  country: 'Canada'}
  ];

  constructor() { }

  ngOnInit() {
  }

}
  1. You'll get the following result.

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.