Home > Net >  How to show icons conditionally?
How to show icons conditionally?

Time:07-12

I am trying to implement a small logic, where depending on the API property should be rendered different icons.

The API sends 3 types of media_type:

  • image
  • video
  • album

I just want to display different icons based on those 3 types.

In react.js I would do

    {
     data.media_type==='image'
     ?
      <mat-icon svgIcon="image" aria-hidden="false"></mat-icon>
      :
      data.media_type==='video'
      ?
      <mat-icon>video</mat-icon>
      :
      <mat-icon>album</mat-icon>
      }

How can I do similar in Angular?

Any help will be appreciated.

CodePudding user response:

In Angular you could also have the same implementation. I will mention 3 methods below:

Method 1:

<mat-icon *ngIf="data.media_type==='image'">image</mat-icon>
<mat-icon *ngIf="data.media_type==='video'">movie</mat-icon>
<mat-icon *ngIf="data.media_type==='album'">album</mat-icon>

In this case when data.media_type is image, the image icon is shown and the other two are hidden. The same goes for the other icons as well.

Method 2:

<mat-icon>{{data.media_type==='image' ? 'image' : data.media_type==='video' ? 'movie' : 'album'}}</mat-icon>

Method 3:

In your component you can also define a method that returns the name of the icon you want to be displayed according to data.media_type.

<mat-icon>{{showIcon()}}</mat-icon>

xxx.component.ts:

showIcon():string {
   if (this.data.media_type === 'image') {
       return 'image';
   } else if (this.data.media_type === 'video') {
       return 'movie';
   } else {
       return 'album';
   }
}

My most and least favorite would be method 1 and method 3. In method 3, the method is constantly being executed in your template which is why I think it is not the most efficient method.

  • Related