This is used to implement switch case with html
Syntax:
<tagname [ngSwitch]="varname">
<tagname *ngSwitchCase="value1">..</tagname>
...
<tagname *ngSwitchDefault>...</tagname>
</tagname>
It is actually a combination of two directives i.e. an attribute directive and a structural directive. It is very similar to the switch statement of other programming languages like Java and C# but within a template.
Here, you can also define a default section using the ng-switch-default directive to show a section if no other sections get a match. So, while working with ngSwitch directive, you need three things to keep in mind, they are ngSwitch, ngSwitchCase and ngSwitchDefault.
Example
Now, my requirement is based on the selected course the require topics to be displayed .
.ts Changes
import { Component } from '@angular/core';@Component({selector: 'app-ngswitchdemo',templateUrl: './ngswitchdemo.component.html',styleUrls: ['./ngswitchdemo.component.css']})export class NgswitchdemoComponent {coursename:string="";}.html<select [(ngModel)]="coursename"><option value="">-select course-</option><option>angular</option><option>reactjs</option></select><hr><div style="font-size:x-large" [ngSwitch]="coursename"><ul *ngSwitchCase="'angular'"><li>databindings</li><li>directives</li><li>routing</li></ul><ul *ngSwitchCase="'reactjs'"><li>databindings</li><li>axois</li><li>redux</li></ul><span *ngSwitchDefault>select course to get details..</span></div>Outputnote: ----- *user selected list item with in dropdown list will be assigned to course name variable by ngModel[two-way databinding] *whenever course name variable value changes,ngswitch will be executed,it will verify | compare course name variable value with ngswitchcase, matching ul tag will be loaded for presentation
Example 2.ts changesimport { Component } from '@angular/core';@Component({selector: 'app-ngswitchdemo',templateUrl: './ngswitchdemo.component.html',styleUrls: ['./ngswitchdemo.component.css']})export class NgswitchdemoComponent {public dropDownValue = "";SetDropDownValue(drpValue : any) {this.dropDownValue = drpValue.target.value;}}.html Changes<select (change)="SetDropDownValue($event)"><option value="">Select</option><option value="In">In</option><option value="US">US</option><option value="UK">UK</option></select><h2>You Have Selected</h2><div [ngSwitch] = 'dropDownValue'><h3 *ngSwitchCase="'In'">India</h3><h3 *ngSwitchCase="'US'">United State</h3><h3 *ngSwitchCase="'UK'">United Kingdom</h3><h3 *ngSwitchDefault="">You have not selected any country</h3></div>Output
No comments:
Post a Comment
Thank you for visiting my blog