How to use *ngSwitch in Angular 2+ Versions

Switch case is very popular among many languages weather on client side or server side. A switch provides flexibility to validate a section according to expressions. In this post, we will discuss the implementation of Switch cases in Angular 7 latest version.

*ngSwitch in Angular 2+ Versions

*ngSwitch workes on expressions, we can have multiple sections wrapped in various switch cases which can be shown according to truth expression.

NgSwitch takes a value which shows the view having a matching expression in switch cases.

<container-element [ngSwitch]="switch_expression">
  <some-element *ngSwitchCase="match_expression_1">...</some-element>
  <some-element *ngSwitchCase="match_expression_2">...</some-element>
  <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
  <ng-container *ngSwitchCase="match_expression_3">
    <!-- use a ng-container to group multiple root nodes -->
    <inner-element></inner-element>
    <inner-other-element></inner-other-element>
  </ng-container>
  <some-element *ngSwitchDefault>...</some-element>
</container-element>

 

Here [ngSwitch] takes a value, which then matched in expression defined in *ngSwitchCase. If none of the expression matches then ngSwitchDefault view will be shown.

So let's fill up above HTML with test expressions

    <div [ngSwitch]="switch_expression">
        <div *ngSwitchCase="'match_expression_1'">match_expression_1</div>
        <div *ngSwitchCase="'match_expression_2'">match_expression_2</div>
        <div *ngSwitchCase="'match_expression_3'">match_expression_3</div>
        <ng-container *ngSwitchCase="'match_expression_3'">
          <!-- use a ng-container to group multiple root nodes -->
          <div>match_expression_3 inner-element</div>
          <div>match_expression_3 inner-other-element</div>
        </ng-container>
        <div *ngSwitchDefault>Default</div>
    </div>

 

Give switch_expression in component a value to show matching element.

....
....
export class AppComponent {
  switch_expression:string;


  constructor(){
    this.switch_expression = "match_expression_2";
  }	
...
...

Now only "match_expression_2" will be visible as a matching case.

So here we discussed a quick example of ngSwitch in Angular 2+ versions.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments