☰ See All Chapters |
Angular ngSwitch Directive
Switch statements are used to process one of many blocks and block being selected matches the provided condition. The angular ngSwitch directive inserts one of many elements to the DOM. The ngSwitchCase directive serves the same purpose as a case option in the switch statement. ngSwitchDefault serves the same purpose as default in the switch statement.
Syntax:
<container_element [ngSwitch]="switch_expression"> <inner_element *ngSwitchCase="match_expresson_1">...</inner_element> <inner_element *ngSwitchCase="match_expresson_2">...</inner_element> <inner_element *ngSwitchCase="match_expresson_3">...</inner_element> <inner_element *ngSwitchDefault>...</element> </container_element> |
Angular ngSwitch Directive Example
app.component.ts
import { Component } from '@angular/core';
@Component({ selector: 'app-tag', template: ` Input string : <input type='text' [(ngModel)]='num' /> <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 *ngSwitchDefault>This is Default</div> </div> ` }) export class AppComponent { num: string=''; } |
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
index.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Angular Example</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-tag></app-tag> </body> </html> |
Output
All Chapters