Uses of NgSwitch NgStyle, NgClass in Angular 2/4/5

In my last article I discussed on build in directive NgFor & NgIf.  In these article i discuss on NgSwitch, NgStyle, NgClass.

    1. ngSwitch : Switch we have used for different actions based on the conditions.
      For example we have display different persons form different country with different colors. Let we have below persons array.

      class SwitchComponent {
      persons: any[] = [
      "name": "Andrew",
      "states": 'UK'
      "name": "Jacob",
      "country": 'USA'
      "name": "Aamka",
      "country": 'CA'
      "name": "Kangna",
      "country": 'IND'
      "name": "William",
      "country": 'USA'
      "name": "Palak",
      "country": 'IND'

      In Template you need to code like below way.

      <ul *ngFor="let person of persons" [ngSwitch]="">
      <li *ngSwitchCase="'IND'" class="alert alert-success">{{}}</li>
      <li *ngSwitchCase="'UK'" class="alert alert-warning">{{}}</li>
      <li *ngSwitchCase="'USA'" class="alert alert-danger">{{}}</li>
      <li *ngSwitchCase="'CA'" class="alert alert-info">{{}}</li>
      <li *ngSwitchDefault class="alert alert-primary">{{}}</li>

      for switch case you need to add directive [ngSwitch] then pass the value to check conditions then you need to check that condition using *ngSwitchCase for different conditions & you add default case using *ngSwitchDefault.

    2. ngStyle: Using this directive you can add style element to your element.

      <div [ngStyle]="{'background-color':'black'}"></div>

      In above syntax you can easily add backround color using ngStyle. Now in below example you can use conditionally apply color for the div using ngStyle

      <div [ngStyle]="{'color': === 'IND'? 'Green' : 'gray' }"></div> 

      Also you can pass the function on the conditions like below.

      <div [ngStyle]="{'color': getCountryColor(}"></div> 

      In that you can pass function name that created in the component. like

          switch (countryname) {
            case 'IND':
              return 'orange';
            case 'UK':
              return 'black';

    3. ngClass :Using this directive you can add class on you elements.

      <div [ngClass]="{'bg-red' === 'IND'}"> India </div>

      First value is class name then condition to display that class. In above example when country name is “IND” then it display class “bg-red”.

      Also you can use function instead of the conditions like below

      <div [ngClass]="{'bg-red': getCountry(}"> India </div>
Spread the love