Showing the Enum name rather than the value in an Angular HTML template for a bound Typescript Interface

After retrieving an array of objects with various properties from a .NET Controller, I am utilizing the following Typescript code:

import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-fetch-data',
  templateUrl: './fetch-data.component.html'
})
export class FetchDataComponent {
  public celebreties: Celebrety[];

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<Celebrety[]>(baseUrl + 'celebrety').subscribe(result => {
      this.celebreties = result;
    }, error => console.error(error));
  }
}
export enum Gender {
  Male = 0,
  Female = 1,
  Unknown = 2,
}
interface Celebrety {
  name: string;
  birthDate: Date;
  gender: Gender;
  role: string;
  imageUrl: string;
}

The HTML template structure is as follows:

<h1 id="tableLabel">Celebereties</h1>

<p *ngIf="!celebreties"><em>Loading...</em></p>

<table class='table table-striped' aria-labelledby="tableLabel" *ngIf="celebreties">
  <thead>
    <tr>
      <th>Name</th>
      <th>Birth Date</th>
      <th>Gender</th>
      <th>Role</th>
      <th>Image</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let celebrety of celebreties">
      <td>{{ celebrety.name }}</td>
      <td>{{ celebrety.birthDate }}</td>
      <td>{{ celebrety.gender }}</td>
      <td>{{ celebrety.role }}</td>
      <td><img src="{{ celebrety.imageUrl }}"/></td>
    </tr>
  </tbody>
</table>

While attempting to display the gender names instead of numbers, using {{ Gender[celebrety.gender] }} resulted in an undefined error. Why do you think the enum is not recognized within the Angular brackets?

Answer №1

I discovered a clever workaround. I created a function that retrieves the data and then implemented it in the HTML:

<h1 id="tableLabel">Celebrities</h1>

<p *ngIf="!celebrities"><em>Loading...</em></p>

<table class='table table-striped' aria-labelledby="tableLabel" *ngIf="celebrities">
  <thead>
    <tr>
      <th>Name</th>
      <th>Birth Date</th>
      <th>Gender</th>
      <th>Role</th>
      <th>Image</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let celebrity of celebrities">
      <td>{{ celebrity.name }}</td>
      <td>{{ celebrity.birthDate | date }}</td>
      <td>{{ GetGenderNameByValue(celebrity.gender) }}</td>
      <td>{{ celebrity.role }}</td>
      <td><img src="{{ celebrity.imageUrl }}" /></td>
      <td><button class="btn btn-primary" (click)="Delete()">Delete</button></td>
    </tr>
  </tbody>
</table>
<button class="btn btn-primary" (click)="Reset()">Reset</button>
import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-fetch-data',
  templateUrl: './fetch-data.component.html'
})
export class FetchDataComponent {
  public celebrities: Celebrity[];

  public Reset() {
  }
  public Delete() {
  }
  public GetGenderNameByValue(value : number) {
    return Gender[value];
  }

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<Celebrity[]>(baseUrl + 'celebrity').subscribe(result => {
      this.celebrities = result;
    }, error => console.error(error));
  }
}
export enum Gender {
  Male,
  Female,
  Unknown,
}
interface Celebrity {
  name: string;
  birthDate: Date;
  gender: Gender;
  role: string;
  imageUrl: string;
}

Answer №2

Enums were originally intended for a different purpose, but it is possible to use them in this way:

Object.keys(Gender)[Object.keys(Gender).length / 2 + celebrety.gender]

https://i.sstatic.net/JPq1g.png

The code above assumes that celebrety.gender is a number (the value assigned from the enum). If it is actually text, you would do:

Object.keys(Gender)[Object.keys(Gender).length / 2 + Gender[celebrety.gender]]

This method may seem unnecessary since you already have the text "male"/"female"/"unknown."

Using enums in this manner can appear unconventional because they are typically used at compilation time rather than as objects.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strategies for implementing ID passing in Angular's Ngrx effects

To show the information of the selected list, I will be choosing a list first. ...

Compiling TypeScript: Using the `as` operator to convert and then destructure an array results in a compilation error, requiring an

I am currently utilizing TypeScript version 2.9.2. There is a static method in a third-party library called URI.js, which is declared as follows: joinPaths(...paths: (string | URI)[]): URI; I have a variable named urlPaths that is defined as urlPaths: s ...

Modifying the form-data key for file uploads in ng2-file-upload

I have implemented the following code for file upload in Angular 2+: upload() { let inputEl: HTMLInputElement = this.inputEl.nativeElement; let fileCount: number = inputEl.files.length; let formData = new FormData(); if (fileCount > 0) { // a f ...

Implement conditional props for a React component by linking them to existing props

In my current project, I am working on a component that has a loading state. The component has an isLoading prop which determines whether the component is currently in a loading state or not: interface CustomImageComponentProps { isLoading: boolean ...

Top method for changing classes in Angular

Within my Angular4 application, I've implemented a method to conditionally apply two classes as seen below: <some-element [ngClass]="{ 'fa-toggle-on': category.active, 'fa-toggle-off': !category.active }"> </some-element& ...

Unable to globally install @angular/cli using Node.js on Red Hat software collection

After installing node.js 8 from Red Hat Software Collection (rh-nodejs8), I encountered an issue where I couldn't globally install TypeScript or @Angular/CLI because my bash session was restricted by scl-utils, requiring admin rights for global instal ...

A guide on determining the number of rows in an ag-grid with TypeScript and Protractor

I am currently working on extracting the number of rows in an ag-grid. The table is structured as follows: <div class="ag-body-container" role="presentation" style="height: 500px; top: 0px; width: 1091px;"> <div role="row" row-index="0" row-id="0 ...

I am unable to utilize NavLink unless it is within the confines of the <Router> component

I am currently developing a React application using react-router-dom. To enhance the user experience with smooth transitions, I integrated framer-motion for page animations. However, I encountered an issue where my navbar was being animated and recreated e ...

Display an API generated popup list using Vue's rendering capabilities

I'm attempting to generate a pop-up within a displayed list using custom content retrieved from an API request. Currently, my code looks like this: <template> <div class="biblio__all"> <a v-for="i in items" ...

Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS. My goal is to integrate this ...

Troubleshooting: Issue with Button Layout in Ionic's ItemSliding Component

How can I create a list item that allows swiping to reveal an archive button? The requirement is for the icon to appear to the left of the text. I'm referring to the documentation on Button Layout: https://ionicframework.com/docs/api/components/item ...

Retrieve a specific JSON object by ID in an Angular Typescript observable

Below is a json string that contains both "stocks" and "contacts" data arrays. Depending on the request, I need to extract either the "stocks" or "contacts" data: [{ "id": "stocks", "name": "Stocks", "data": [ { "id": 1, "name": "Act ...

Utilize Typescript to aim for the most recent edition of EcmaScript

Are you looking to configure your typescript build to compile to the most recent version or the most current stable release of EcmaScript? For example, using this command: tsc --target <get latest version> Alternatively, in a tsconfig file: { & ...

Implementing optional default values in React props using conditional types

I have a dilemma with conditional props types When attempting to set a default value for my optional prop within the conditional type, it causes issues with the types export type ChatBase = { id: string; title: string; } type ChatCardProps = { title: ...

p-menu fails to appear

I'm currently experimenting with Primeng and Angular 2 to put together a basic menu. Take a look at my code snippet: import {Component, OnInit} from '@angular/core'; import {Menu, MenuItem} from 'primeng/primeng'; @Component({ ...

TS - deduce the specific type of a key value without receiving a union type

Welcome to the coding playground: Click here to start coding Let's talk about a scenario where a function is expected to return some value based on an input argument. The challenge arises when there are keys with the same name but different types re ...

Testing the Click() function in Angular2 using keypress event

I am currently working on testing a sorting feature for a table. This particular table allows for sorting based on both a primary and secondary value, with the secondary value being selected by holding down the shift key. In order to set the sort order, I ...

Adjust the colors of two elements by clicking a button's onclick event

As stated in the title, I have a button in the books component. When this button is clicked, the color of a div within the books component and another div in the navbar component should change. - Below is the code for the books component : export class Bo ...

Angular webpack starter - $ definition

I created a new app using the Angular 2 Starter by AngularClass. When I open the console (in both Chrome and Firebug), I can type: a = $('body') The variable a appears to be an object that looks like a DOM element. However, I am unable to run ...

Preventing CSRF, XSRF, and XSS with Angular JWT stored in a Cookie

I'm currently learning Angular and Express, and I am working on implementing a login feature. From what I've gathered, it is recommended to store JWT in cookies with the settings "secure: true" and "httpOnly: true," like so: const jwtBearerToke ...