Search code examples
angularangular-ng-if

*ngIf of angular2 to test on three different values of the same attribute


I'm new to angular2 , and I want to use *ngIf but in a little different way and it does not work. So, I have an attribute type within an object item, this type could only have one of those three strings :

  1. type_A
  2. type_B
  3. unspecified

And depending on the value of item.type an image would be shown. I'd used it this way but seems doesnt work (images are not displayed):

<li *ngIf="item.type === type_A">
   <img src="assets/images/typeA-icons.png"/>
</li>
<li *ngIf="item.type === type_B">
    <img src="assets/images/typeB-icons.png"/>
</li>
<li *ngIf="item.type === unspecified">
    <img src="assets/images/unspecified-icons.png"/>
</li>

Any help how could I achieve that ?


Solution

  • First of all you should wrap your strings to quotes

    item.type === 'type_A'
    

    instead of

    item.type === type_A
    

    You are looking for ngSwitch operator https://angular.io/docs/ts/latest/api/common/index/NgSwitch-directive.html

    <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>