简体   繁体   English

如何将基于 typescript 决策的值返回到我的模板?

[英]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.

相关问题 如何根据值返回颜色为 angular 的文本 - How can I return text with color angular based on value 如何在我的模板(Angular2 / TypeScript)中将HTML字符串转换为HTML? - How can I convert strings of HTML into HTML in my template (Angular2/TypeScript)? Angular - 如何从 typescript 访问模板变量/引用? - Angular - How can I access Template variable/reference from typescript? 我如何使用不同的html模板为相同的打字稿文件? - How i can use differents html template for the same typescript file? 如何在打字稿中动态返回对象键的值? - How do I return value of a key of an object dynamically in typescript? 解决 Angular Typescript 承诺后如何返回值? - How do I return a value after promise is resolved Angular Typescript? 我如何检查模板并获得它的价值? - How can i check Template and get the value of it? Angular2-指令。 如何将指令中的值传递给模板? - Angular2-directives. How can I pass the value into the template from my the directive? 如何在Typescript中向基于json的对象添加更多数据? - How can I add more data to an json based object in Typescript? 如何获取 I18n 变量值我可以返回到我的 Angular 父组件? - How to get a I18n variable value I can return to my Angular parent component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM