NgSwitch :
The ng-switch is one type of directive. ng-switch is depending on an expression.HTML elements switch case expression to match with ngSwitch expression. When expressions are match with case, that NgSwitchCase template is rendered.
In this article we are learn how to use onclick event ng-switch case and on select option ng-switch case in angular.
here, we are update app.component.ts file using below code :
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { clickView:any selectView:any changecase($event: any) { this.clickView = $event.target.value } changeView($event:any){ this.selectView = $event.target.value } }
Ans also update app.component.html file using below code :
<div class="wrapper"> <h2>NgSwitch In Angular</h2> <h3>Onclick Switch Case</h3> <ng-container> <button (click)="clickView='test1'" class="mx-1 btn btn-primary">test 1</button> <button (click)="clickView='test2'" class="mx-1 btn btn-success">test 2</button> <button (click)="clickView='test3'" class="mx-1 btn btn-danger">test 3</button> <button (click)="clickView='test4'" class="mx-1 btn btn-warning">test 4</button> <button (click)="clickView='test5'" class="mx-1 btn btn-dark">test 5</button> </ng-container> <ng-container [ngSwitch]="clickView"> <p class="mt-2" *ngSwitchDefault>I am ...</p> <p class="mt-2" *ngSwitchCase="'test1'">I am test 1.</p> <p class="mt-2" *ngSwitchCase="'test2'">I am test 2.</p> <p class="mt-2" *ngSwitchCase="'test3'">I am test 3.</p> <p class="mt-2" *ngSwitchCase="'test4'">I am test 4.</p> <p class="mt-2" *ngSwitchCase="'test5'">I am test 5.</p> </ng-container> <h3>Select Switch Case</h3> <ng-container> <select (change)="changeView($event)"> <option value="test1">test1</option> <option value="test2">test2</option> <option value="test3">test3</option> <option value="test4">test4</option> <option value="test5">test5</option> </select> </ng-container> <ng-container [ngSwitch]="selectView"> <p class="mt-2" *ngSwitchDefault>I am ...</p> <p class="mt-2" *ngSwitchCase="'test1'">I am test 1.</p> <p class="mt-2" *ngSwitchCase="'test2'">I am test 2.</p> <p class="mt-2" *ngSwitchCase="'test3'">I am test 3.</p> <p class="mt-2" *ngSwitchCase="'test4'">I am test 4.</p> <p class="mt-2" *ngSwitchCase="'test5'">I am test 5.</p> </ng-container> </div>
Now run our project using npm start :