Choose from the Angular enum options

I am working with an enum called LogLevel that looks like this:

export enum LogLevel {
    DEBUG = 'DEBUG',
    INFO = 'INFO',
    WARNING = 'WARNING',
    ERROR = 'ERROR'
}

My goal is to create a dropdown select element in my form, where each option displays the enum text as its label. Here is what I have so far:

<select>
     <option value="DEBUG">DEBUG</option>
     <option value="INFO">INFO</option>
     <option value="INFO">INFO</option>
     <option value="INFO">INFO</option>
</select>

Can anyone suggest a more efficient way to achieve this?

Answer №1

Consider utilizing Object.values for transforming the enum into an array:

    <select>
      <option *ngFor="let logValue of Object.values(LogLevel)" [ngValue]="logValue">{{}logValue}</option>
   </select>

Answer №2

Here's a straightforward solution:


 1. Content of app.component.ts:

export class AppComponent {
  keys = Object.keys;
  logLevel = LogLevel;

  selected = LogLevel.DEBUG;

  select(event: any) {
    const value = event.target.value;
    this.selected = value;
    console.log(this.selected);
  }
}

export enum LogLevel {
  DEBUG = 'DEBUG',
  INFO = 'INFO',
  WARNING = 'WARNING',
  ERROR = 'ERROR',
}

 2. Content of app.component.html

<select [(ngModel)]="selected" (change)="select($event)">
  <option *ngFor="let log of keys(logLevel)" [value]="logLevel[log]">
    {{ log }}
  </option>
</select>

For more information, please visit this link https://stackblitz.com/edit/angular-ivy-cuhnbw

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

Javascript and JSON: Making Updates to Files

Working on a program, I am faced with an issue while sending a literal variable to local storage using JSON.stringify. My goal is to continuously update the local storage and append to the existing data stored. The problem arises during the parsing of the ...

Replicate the anchor's functionality (opening in a new window when 'ctl' is pressed) when submitting a form

I have a question that may seem unconventional - Is there a graceful method to replicate the functionality of an anchor tag when submitting a form? I want users to be able to hold down the control key while submitting a form and have the result open in a ...

When forcibly closing a window, the disconnect event for Socket.IO sockets may not trigger as expected

Currently in the process of creating chat rooms with Socket.io. I've had good success so far, as it's user-friendly and well-documented. However, I've noticed that if I reload the page, wait for the socket to connect, and then close the w ...

Creating callback functions that vary based on input variables

Consider the following code snippet, which may seem somewhat contrived: arbitraryFunction( // Input that is dynamically generated [ returnValue("key1", "a"), returnValue("key2", 1), returnValue ...

Passport.js simply redirects to the failure page without invoking the LocalStrategy

I'm facing a persistent issue with Passport.js in my Express.js small application. No matter what I input in the LocalStrategy, I always end up being redirected to the failureRedirect without seemingly passing through the LocalStrategy at all. What am ...

best method for embedding javascript code within html (within a script tag)

In my quest to create dynamic HTML using jQuery and insert it into a specific div on my website, I encountered an issue. Specifically, I am attempting to generate an anchor element where both the href and label are determined by JavaScript variables. Here ...

What is the process for causing an Observable that already exists to emit specialized data?

Let's say I have an Observable that was created in the following way: let observable = of(mockData).pipe(delay(5000)); Is there a method to emit a new value to the observers who are currently subscribed to this observable at a later time? I came acr ...

.NET Core ViewModel with IFormFile attribute causing AJAX Request to freeze

Users now have the option to upload images for a retail product within an Add/Edit Product modal. Product Modal ViewModel: public class ProductModalViewModel { public ProductModalViewModel() { Product = new ProductDTO(); Images = ...

Angular: Implementing a dialog in a component with an established constructor

Within my current component, I have implemented a constructor that injects TestService. However, I now need to add a button that will open a popup dialog. How can I achieve this without interfering with the existing constructor? Thank you for your help. ...

Incorporate a Google Chart link by integrating it with a select handler

I'm facing an issue while trying to open a link in a Google line chart using the selection handler. The chart stops rendering, and as a newcomer to javascript, I'm unsure why. This is how the code is integrated into my HTML: <pre><code ...

Showing an error message with matInput instead of a form control - is this possible?

Within my Material table, I am utilizing the following code: <ng-container matColumnDef="columnDef"> <th mat-header-cell *matHeaderCellDef>Column heading</th> <td mat-cell *matCellDef="let row"> <mat-form-field> ...

Guide to parsing JSONP information using Express

I am attempting to transfer data from phonegap to an express application. Below is the code I am using: Phonegap: $.ajax({ type: 'POST', url:"http://127.0.0.1:3000/test", data: {"test":"this works!"}, dataTyp ...

Stripping the prefix from a string using the .split function leads to an error message stating "Unexpected

When dealing with a string containing a unique prefix, I attempted to separate it into an array after the backslash character "\" by using the split function. Here is the string: i:0#.w|itun\allepage_fg This was my approach: function claimOrder ...

Once the recursive function executes (utilizing requestAnimationFrame), socket.emit can finally be triggered

My current issue involves sending an array to my server from the client side using a recursive function, but the responses from the server are delayed and only arrive after the recursive function completes. I'm uncertain whether the problem lies with ...

The data-src tags are functioning properly in the index.html file, but they are not working correctly in angular

I'm still learning about Angular and JavaScript, so please bear with me if my questions seem silly. I've been trying to add a theme to my Angular project. When I include the entire code in index.html, everything works fine. However, when I move ...

Having trouble resolving the error "Cannot find name CSSTranslate" while working with VSCode and tsc? Let's tackle this issue together

My program runs smoothly in a development environment and appears flawless in VSCode, but I'm encountering issues with tsc pointing out unknown names and properties. It's puzzling because my file doesn't seem to have any problems in VSCode. ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

What is the best way to dynamically import two css frameworks in React?

Currently, I am involved in a project that requires me to incorporate a button for toggling between Bootstrap and Foundation at the request of my client. After exploring several alternatives, I have determined that utilizing hooks to manage the state of e ...

Tips for implementing daterangepicker js in an Angular 2 project

I'm currently working on an Angular 2 project and I'm looking to integrate the daterangepicker.js library for a date range picker. If you're not familiar with it, you can find more information about the library here. Here's the HTML co ...

Comparing Fetch and Axios: Which is Better?

Currently delving into the realms of axios and the fetch API, I am experimenting with sending requests using both methods. Here is an example of a POST request using the fetch API: let response = await fetch('https://online.yoco.com/v1/charges/&ap ...