Home > other >  How to Display an Enum entity Name in Angular/TypeScript?
How to Display an Enum entity Name in Angular/TypeScript?

Time:11-14

I'm trying to Display the Name of my Enum Entity within an 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:

public get Type() {
  return Type; 
}

Now i'm trying to Display the Name of the Entry "Tool_H". But is there a way the get the String "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"

CodePudding user response:

if you use something like this Type['TOOL_H'] in html you get 'Some..', so it's useful for showing your enum.

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

CodePudding user response:

(First, a piece of advice: I wouldn't use a name like 'Type' for my 'code-stuff-naming', so similar to some possible Angular reserved word).

I guess you are giving the same name to your enum (Type) and to your 'Type' variable (with the 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>
...

  • Related