Retrieving the value from a string Enum in Angular based on an integer

export enum RoleTypesEnum {
    RoleA = 'Role is A',
    RoleB = 'Role is B',
}

// in TypeScript file
public RoleTypesEnum = RoleTypesEnum;

I am trying to obtain the string value (e.g. Role is B) from an enum using an integer.

If I use the following code in my HTML or TypeScript file: console.log(RoleTypesEnum[0]) it returns undefined.

This issue arises because I receive integers from the backend (e.g., through JSON -> RoleTypes: 0 or 1).

While I can create a pipe to fetch enum values using Object.values(RoleTypesEnum);, I'm curious about best practices. The pipe solution can be found here: Angular Pipe extracts from Enum values, but generic for any Enum

Ensuring Backend-Frontend Synchronicity

The database stores enums as integers. In the backend (ASP.NET), DTOs and models have fields with enum types. Upon returning from the Controller, it automatically converts the enum into an integer in the JSON response.

  1. If I were to return the string value from the backend (json: "roleB") instead of the integer (json: 1), I would need to convert the enum into a string before sending the JSON, which might complicate the DB and backend design.
  2. In the case of returning an integer from the backend (as seen in the current scenario), custom string values cannot be utilized. For instance, retrieving 'RoleTypesEnum[1]' results in undefined. Unless I reset the enum to work solely with integers
export enum RoleTypesEnum {
    RoleA = 0,
    RoleB = 1,
}

However, this approach eliminates the possibility of using custom string values (e.g. "Role is B").

Answer №1

Successfully implemented custom string values using this method:

Shared/enums-descriptions.ts

export const MyTypesEnumDescription: {
    [key in MyTypesEnum]: string;
} = {
    [MyTypesEnum.Standard]: 'Standard',
    [MyTypesEnum.Advanced]: 'Advanced Stage',
    [MyTypesEnum.Intermediate]: 'Intermediate Stage',
};

MyClass.ts

public selectBoxItemList = [
    new SelectListItem({
        value: MyTypesEnum.Advanced,
        text: MyTypesEnumDescription.InvalidCall,
    }),     

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

Not all generic types specified with an extends clause are appropriately narrowed down as expected

Consider the following scenario: type MyType = 'val1' | 'val2' | 'val3'; const variable = 'val1' as MyType; const val2 = 'val2'; const val3 = 'val3'; declare function test<U extends MyType&g ...

Troubleshooting Angular Reactive Forms: Issue with Binding Dynamic Select Dropdown Value

I currently have two arrays of data: AssociatedPrincipals, which contains previously saved data, and ReferencePrincipals, which consists of static data to populate dropdown controls. I am facing difficulties in displaying/selecting the previous value from ...

Identifying the pressed key on a mouse click event using Angular 2

I am working on an Angular 2 component that has a div element bound to a click event: <div #myDiv class="myClass" (click)="addAnnotation($event)"> </div> When the div is clicked, I want the addAnnotation code to run only if the 'a&ap ...

Establishing the context for the input template by utilizing ng-template, ng-container, and ngTemplateOutlet

I am facing a challenge with a customizable component that utilizes an ng-container to display either a default template or a template passed in as an input. The issue arises when I try to set the context of the passed-in template to the nesting component ...

Utilize Lambda Layer to seamlessly share interfaces/types across Lambda Functions

I have a lambda layer file that contains an enum definition (which will be used in various lambda functions) as shown below: exports enum EventTypes { Create, Delete, Update, } Initially, everything was working well as I tested ...

Having trouble binding component property in VueJS with TypeScript?

Why is my component property not binding when I set the related component attribute to a value? Even when inspecting with Vue devtools or outputting the value into the HTML, it remains at the default value set on the component. I tried setting a string at ...

Retrieve the attribute of a JSON data structure

I'm encountering an issue while trying to access the property of a JSON object named date in my Angular 6 project. Even though I assigned a variable to it, it keeps showing up as undefined. This is the snippet of code causing trouble: getHistorial(d ...

What is the process for inputting a predefined function into an interface?

In my project, I have a Locale interface that defines the properties of a locale for my component: interface Locale { src: string; alt: string; language: string; i18nFormat: string; } During debugging, I am using the built-in .toSource() function ...

Make the angular component refresh when the back button is pressed

I am working on a TeamSeasonComponent with the URL http://localhost:4200/teams/season/<team_id>. On this page, there are links to other team's pages which would take me to http://localhost:4200/teams/season/team_2_id>. I switch between these ...

Exploring Angular localization using ng2-smart-table

Currently, I am utilizing ng2-smart-table. In my component.ts file, I am setting the column headings. settings = { actions: { add: false, edit: false, delete: false }, columns: { date: { title: 'Date' ...

Can a lightweight database be utilized in a Nativescript project focused on code sharing?

Currently, I am in the process of launching a new code sharing project using nativescript. My main goal is to create an offline app suitable for both tablets and desktops. I have successfully implemented code sharing following this guide: . Now, my focus ...

What is the proper way to utilize bootstrap dropdown menus?

I need to create a dropdown menu similar to the one shown in this image: I attempted to use code from the following URL: https://getbootstrap.com/docs/4.0/components/dropdowns/, but unfortunately, it did not work as expected even though I have installed B ...

Exploring the parent-child relationship of three components within Angular 2

Currently, I am developing a shopping cart using Angular 2. The application consists of two components - one for categories and another for product listings, both included in the main app component as children. However, I'm facing an issue where these ...

The ESLint tool seems to be struggling to detect the package named "@typescript-eslint/eslint-plugin"

Struggling with getting ESLint to function properly on a new Angular project in VS Code. The error message I keep encountering is about failing to load "@typescript-eslint/eslint-plugin". After spending the past 3 hours troubleshooting, I have searched hig ...

Unexpected termination during the npm installation process without providing a clear error message

Every time I try to create a new Angular2 app using the command ng new new-app, angular-cli successfully generates the necessary files and then proceeds to run npm install. However, the npm install process abruptly stops with no error message provided. As ...

Encountered an error while attempting to install the 'ionic-native' package

Currently, I am navigating through this particular link to integrate local notifications into my Ionic 2 application. To kickstart the process, I executed the following two commands: Username@DESKTOP-BNKQVBC MINGW64 ~/Reminder-App (platform-specific) $ n ...

Delete a specific element from an array using a specified criteria

I'm attempting to remove a specific item from an array based on the selected option. To better understand, take a look at this code: component.html <fnd-extended-select label="Tipo Prodotto:" [(ngModel)]="landingType" name="tipoprodotto"> ...

Exploring a specified set of numbers with PrimeNG's input number spinner for looping

Is there a way to iterate through a series of numbers, such as from 0 to 10, using the PrimeNG input number spinner? ...

How can we determine the type of InertiaFormProps in Laravel Inertia?

I have a webpage with a useForm hook implemented, featuring a multi-step form split into separate components. Here's an example: export default function create(){ const form = useForm({ name: '', content: &ap ...

Sign up for notifications about updates to a variable within an Angular service

Is there a way to track changes in the value of a variable within an Angular service? I've been searching for a solution, but haven't been able to find one yet. In my layout's header component, I have a counter that displays the number of ...