简体   繁体   中英

How i can return to my template a value based in a typescript decision?

I have one service that returns an JSON with a property called name .

I'm doing a *ngFor in this JSON in my template and based in the name property, i need to show a specific material icon.

I tried to create a function getIcon() that receives the name and return the specific icon:

TS:

getIcon(name: string): string {
   if (name === 'h01') {
      return 'home'
   }
   else if (name === 'c30') {
       return 'clipboard'
   }
}

Template:

 <mat-icon aria-hidden="false">{{ getIcon(myJson.name) }}</mat-icon>

But everytime that i do one action in my screen, eg click in a button, this function is called again several times, so, i'm searching if have a better way to do this.

You can solve the problem using Angular pipes

src/app/pipes/icon-name.ts

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'iconName',
  pure: false // detect object change
})
export class IconNamePipe implements PipeTransform {
  transform(value: string, fallback: string = ''): string {
    if (name === 'h01') {
      return 'home';
    }
    else if (name === 'c30') {
       return 'clipboard';
    }
    return fallback;
  }
}

template

 <mat-icon aria-hidden="false">{{ myJson.name | iconName: 'default-icon' }}</mat-icon>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM