[英]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
.我有一项服务返回 JSON ,其属性名为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.我在我的模板中的这个 JSON 中做一个*ngFor
并基于name
属性,我需要显示一个特定的材料图标。
I tried to create a function getIcon()
that receives the name and return the specific icon:我尝试创建一个接收名称并返回特定图标的 function getIcon()
:
TS: 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.但是每次我在我的屏幕上做一个动作,例如点击一个按钮,这个 function 被再次调用几次,所以,我正在寻找是否有更好的方法来做到这一点。
You can solve the problem using Angular pipes您可以使用 Angular管道解决问题
src/app/pipes/icon-name.ts 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.