简体   繁体   English

如何在 Angular/TypeScript 中显示枚举实体名称?

[英]How to Display an Enum entity Name in Angular/TypeScript?

I'm trying to Display the Name of my Enum Entity within an AngularApp.我正在尝试在 AngularApp 中显示我的枚举实体的名称。

This is my Enum:这是我的枚举:

export enum Type{
  All = 'All',
  TOOL_H = 'Some..',
  TOOL_B = 'Stuff.."',
  TOOL_S = 'to..',
  TOOL_C = 'Show..',
}

in my app.component.ts i've added an method which returns an object of the Enum:在我的app.component.ts 中,我添加了一个返回枚举对象的方法:

public get Type() {
  return Type; 
}

Now i'm trying to Display the Name of the Entry "Tool_H".现在我正在尝试显示条目“Tool_H”的名称。 But is there a way the get the String "Some..."?但是有没有办法得到字符串“Some...”?

I've also tried it with this statement, but nothing appears on the Page我也用这个语句尝试过,但页面上没有出现任何内容

<div *ngIf="tool.type === Type.TOOL_H">Some...</div>

If i'm just use the {{ tool.type }} it displays "Tool_H"如果我只是使用 {{ tool.type }} 它会显示“Tool_H”

如果你在 html 中使用类似Type['TOOL_H'] ,你会得到'Some..' ,所以它对于显示你的枚举很有用。

<span>{{Type['TOOL_H']}}</span> // resault: 'Some..'

(First, I little piece of advise, I would never use a name like 'Type' for my stuff, so similar to a possible Angular reserved word). (首先,我的一点建议是,我永远不会为我的东西使用像“类型”这样的名称,因此类似于可能的 Angular 保留字)。

I guess you are giving the same name to your enum (Type) and to your 'Type' variable (with the getter 'get Type()').我猜你给你的枚举(类型)和你的“类型”变量(使用 getter 'get Type()')赋予了相同的名称。

Try something simpler as:尝试更简单的方法:

export enum Type{
  All = 'All',
  TOOL_H = 'Some..',
  TOOL_B = 'Stuff..',
  TOOL_S = 'to..',
  TOOL_C = 'Show..',
}


// NOTE: If you don't have the enum definition in 'app.component.ts', import it with something like:
// import {Type} from '../../commons/enums/...';

// Forget the getter:
//public get Type() {
// return Type; 
// }

public showByType(toolType: string, myTypeSelected: string) {
   return toolType === myType
}

<div *ngIf="showByType(tool.type, Type.TOOL_B)">Some...</div>

Something like this should work well (I'm sorry, I didn't test it).像这样的东西应该可以很好地工作(对不起,我没有测试它)。

For the rest of the cases, you just have to change the enum:对于其余情况,您只需要更改枚举:

<div *ngIf="showByType(tool.type, Type.TOOL_B)">'Stuff.."</div>
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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