Angular/Typescript: Getting the enum name instead of its value in a key-value pair

In my project, I have defined the interfaces Meal and Mealplan to handle data retrieved from an api. Every Mealplan includes key-value pairs, where each key corresponds to a day of the week and is stored in the enum Weekday. Therefore, each Mealplan contains a Meal for each day of the week.

export interface Meal {
  id: number;
  name: string;
}

export enum Weekday {
  Monday = 0,
  Tuesday = 1,
  Wednesday = 2,
  Thursday = 3,
  Friday = 4
}

export interface Mealplan {
  id: number;
  mealsPerWeek: { [key in Weekday]: Meal };
}

Now, I am working on a reactive form where I need to display the different meals from mealsPerWeek and pass the meal along with the numeric value of the weekday using [ngValue]. This information is crucial for deleting a specific meal from mealsPerWeek

<select>
  <option *ngFor="let meal of mealplan?.mealsPerWeek | keyvalue: returnZero"
          [ngValue]="{meal: meal.value, weekday: meal.key}"
          [label]="essen.value.name"></option>
</select>

The issue I'm facing is that the value of weekday is currently displayed as a String like "Monday". I need it to be returned as a numeric value such as 0 for Monday instead. I tried using something like meal.key[key], but it didn't work as expected.

console.log(this.form.meal.value.weekday) // "Monday", whereas I expected 0.

Answer №1

I have developed a demonstration on the stackblitz platform, and it is functioning flawlessly.

 weeklyMenu: WeeklyMenu = {
    id: 10,
    mealsPerDay: {
      [Weekday.Monday]: { id: 0, name: 'Monday meal' },
      [Weekday.Tuesday]: { id: 1, name: 'Tuesday meal' },
      [Weekday.Wednesday]: { id: 2, name: 'Wednesday meal' },
      [Weekday.Thursday]: { id: 3, name: 'Thursday meal' },
      [Weekday.Friday]: { id: 4, name: 'Friday meal' },
    }
  };

Answer №2

If you want to get the desired result, all you need to do is utilize

console.log(Weekday[this.form.meal.value.weekday])
.

My suggestion is to always opt for enums with string values like this:

enum Weekday {
  Monday = "Monday",
  Tuesday = "Tuesday",
  Wednesday = "Wednesday",
  Thursday = "Thursday",
  Friday = "Friday"
}

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

How can I maintain query parameters in a redirected route in Angular 4?

In my app-routing.module.ts file, I have set up a route redirection like this: { path: '', redirectTo: '/home', pathMatch: 'full' } Now, let's say that in my index.html file, I have the line <base href="/mysite"> ...

Create various Angular applications using PowerShell for efficient development

Currently, I am in the process of developing a PowerShell script that sequentially builds three different Angular applications. However, I am running into an issue where only the first app is built and the script stops without any errors or reaching the li ...

Creating Angular components and attaching them to the body tag is a simple yet

My goal is to create a component at the root element of the page. I have come across some resources that are similar to what I need, but they use the DynamicComponentLoader which is now considered deprecated. public component: any; constructor( public ...

Validation of email forms in Angular 5

I have encountered a challenge that I need help with: Using Angular 5 - template driven form In my template, there is an input field with the type email. Here's an example: <input type="email" [(ngModel)]="model.email" #email="ngModel" email /> ...

Utilize Angular 4 to dynamically load templates within a single component

My task is to create a component with multiple HTML templates, each containing at least 20 controls. Depending on certain conditions, a specific template should be loaded. Note: I have opted for 3 different templates because the controls vary based on the ...

Changing the target to a nested component within Angular 4

Within my Angular 4 project, I have a component that is nested inside another. This inner or child component consists of a button, an input field, and a drop-down list. When the button is clicked on the parent page, both the input field and the drop-down ...

Mastering the Correct Usage of AuthGuard

I am facing an issue with implementing authguard in my angular application. I have set up a post request to my spring boot backend, and upon success, I set a value to true which I then check in my canActivate method of the authguard. However, for some reas ...

What is the best way to change a blob into a base64 format using Node.js with TypeScript?

When making an internal call to a MicroService in Node.js with TypeScript, I am receiving a blob image as the response. My goal is to convert this blob image into Base64 format so that I can use it to display it within an EJS image tag. I attempted to ach ...

Coloring the background of a day on the Angular Ng-Bootstrap Datepicker Calendar

Is it possible to customize the background color of days that are more than 1 day away on the ng-bootstrap datepicker calendar? I want them to change color in the same way as when a day is selected. Currently, when a day is selected, the div class changes ...

The function is not properly defined for the provided service

I am facing an issue with a service that is provided in app.module.ts and injected into an exported function within the same module. Despite this setup, when running the code inside MSALInstanceFactory, it is indicating that the service is undefined. impor ...

When the @Input() contains an unaltered boolean value, it does not initiate change detection

I have developed an Angular application featuring a popup component. The visibility of the popups can be controlled both from its parent and the popup itself. app.component.ts import { Component } from '@angular/core'; @Component({ selector: ...

What is the process for creating a unique Vee-Validate rule in TypeScript?

I am in the process of developing a unique VeeValidate rule for my VueJS component written in TypeScript. This rule is designed to validate two fields simultaneously, following the guidelines outlined in VeeValidate - Cross Field Validation. Here is a snip ...

Dealing with errors in Angular when using Firebase and observables can

I'm facing an issue with implementing error detection in Angular Firebase. Whenever new users log in to my website, they encounter a permission error in the database, which is displayed in the console. My goal is to have auth.isApproved return false ...

Page Breaks - Patience in anticipation of dataSource readiness

I am facing an issue with my pagination service and component. The dataSource appears empty when the page is loaded for the first time, but by the second time it is populated and I can display the dataTable and paginate successfully. Is there a workaround ...

Navigating with finesse in Angular2

My goal is to generate dynamic routes using the index names from my elastic index. I successfully implemented dynamic routing by manually adding some names, but encountered an issue when trying to insert routes with my elastic index names. In my app.routi ...

Convert C# delegate into TypeScript

Sample C# code snippet: enum myEnum { aa = 0, bb, cc, } public delegate void MyDelegate(myEnum _myEnum, params object[] _params); public Dictionary<myEnum , MyDelegate> dicMyDelegate = new Dictionary<myEnum , MyDelegate>(); publi ...

Obtain information from a CSV document within Highchart Angular

Is there a way to access and retrieve data from a CSV file stored in the assets folder of my local system? The CSV file contains 5 or 6 columns of information. Important: This is an Angular project, therefore jQuery is not available. ...

How to assign a custom validator parameter to a form group in Angular

I'm in a situation where I have a form group and need to validate the end date so it is not earlier than the start date. The challenge here lies in accessing specific fields when the form group is not yet declared. dateFormGroup: this.fb.group({ ...

Perform an HTTP GET request to a RESTful service with specified parameters using Angular 2

I'm currently facing an issue while attempting to create a GET request to the YouTube Web API. I'm struggling with passing parameters through the http.get function and have confirmed the request is being sent using Fiddler. However, I keep receiv ...

Exploring the Integration of a REST API Client in an Angular 6 Web Portal

I am looking to create a test portal that includes a simplified version of Postman as a page. This feature will allow me to send HTTP requests to third-party clients and receive responses. I plan to use the response values to perform additional functions. ...