1

I am working on an angular app. I have a enum as follows

export class myEnum {
  "status1" = 1,
  "status2"  = 2,
  "status3"  = 3,
  "status4" = 4,
  "status5" = 5
 }

In my html I have a data coming from api and I am using *ngFor to display it as follows:

<div>*ngFor="let mydata of data"</div>

Now this data will have a status field in integer(can access using {{mydata.status}}) which will match above mentioned enum. In my html I want to pass/match this number and display it as string. Suppose from API if status coming as 4, then I want to have a code in which I pass this value and it should match it in enum and display "status4" on screen. How can I do that?

2 Answers 2

1

You are using incorrect syntax for *ngFor loop.

Your Template code will be -

<div *ngFor="let mydata of data">
  {{status[mydata]}}
</div>

and in the .ts file, you can use a const object as a lookup object, so that you can directly access the value by key. In Enums you cannot have a numeric key, so using an object can be an easy and effective choice here.

You can write it as -

const statusLookup = {
    1:'status1',
    2:'status2',
    3:'status3',
    4:'status4',
    5:'status5'
  }

If you still want to use enums for any other specific reason, you can use a custom pipe (to get the key by value from enum) and plug it in the template.

Sign up to request clarification or add additional context in comments.

Comments

0

Your component must look something like this

import { Component } from '@angular/core';

export enum StatusEnum{
   offline = 1,
   online = 2
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})


export class AppComponent  {

  public statusEnum = StatusEnum;
  
  public data = [
    {
      id: 1,
      status: 1
    },
    {
      id: 2,
      status: 2
    }
  ]
}

Then in your view you do something like this:

<div *ngFor="let d of data">
  <p>{{statusEnum[d.status]}}</p>
</div>

Check this out: https://stackblitz.com/edit/angular-ivy-enum-in-template

ps: I named the Enum StatusEnum just for clarity!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.