How to show the different different icons based on API response using *ngFor in angular 8?

Viewed 463

In my project i'am using angular latest version, i fetch one API and i got some response, so i used *ngFor and showed the data in template(HTML) mat-dropdown in angular material. now my question is in based on API response how to show the icon in before the text?

In my API response i have the OS type, based on the OS i have to show that icons.

*ngFor condition:

   <mat-option
      *ngFor="let item of activeItems">
        <i *ngIf="hasIcon" class="fa-{{iconType}}"></i>
        <span [textContent]="item.name"></span>
    </mat-option>

Icon condition:

public items: Page<PageObject>;
public iconType;
getItems() {
   if(this.hasIcon == true ){
     if(this.items.content.filter((item: PageObject) => item['andriod'])) {
       this.iconType = 'andriod';
     } else if(this.items.content.filter((item: PageObject) => item['ios'])) {
        this.iconType = 'ios';
      }
   }
 }

I tried this way but it's applying same icon for all the items. if anyone tell me how to fix this?

1 Answers

You have the same icon for every mat-option because it uses the same property iconType for each element. The possible solution is to have an array instead of a single value. Also, you can create a method that will return an icon based on the item.

Something like this in component

getIconType(item: PageObject): string {
  return item['andriod'] ? 'andriod' : 'ios';
}

Usage in template

<mat-option *ngFor="let item of activeItems">
  <i *ngIf="hasIcon" class="fa-{{ getIconType(item) }}"></i>
  <span [textContent]="item.name"></span>
</mat-option>
Related