How can I present the enum type in a dropdown menu using Angular 5 and TypeScript?

In my Angular 5 application, I have defined an enumeration constant called DateRange.

export enum DateRange {
  TODAY = 'Today',
  THIS_WEEK = 'This Week',
  THIS_MONTH = 'This Month',
  THIS_YEAR = 'This Year'
}

I am looking for a way to display this enumeration in a select box within my component's HTML. Any suggestions on how to achieve this?

The desired output would be:

<select> 
  <option value="TODAY"> Today </option>
  <option value="THIS_WEEK"> This Week</option>
  <option value="THIS_MONTH"> This Month </option>
  <option value="THIS_YEAR"> This Year </option>
</select>

Answer №1

Explain the code snippet below in your HTML file:

<select> 
   <option *ngFor="let selection of Object.keys(selections)" [ngValue]="selection">{{selections[selection]}}</option>
</select>

Implement the following in your component:

selections = SelectionOptions;

Answer №2

To populate your dropdown with the keys of an enum, you can iterate through them and use them as values like so:

<select> 
  <option [value]="key" *ngFor="let key of getKeys(EnumName)">{{ EnumName[key] }}</option>
</select>

In your component.ts file, make sure to include the getKeys function:

getKeys(obj: any) { return Object.keys(obj); }

Also, remember that the enum itself must be a part of this component...

Answer №3

You have the option to transform an enum into a JavaScript object.

Object.values(DateRange); // [ 'Today', 'This Week', 'This Month', 'This Year']
Object.keys(DateRange); // [ 'TODAY', 'THIS_WEEK', 'THIS_MONTH', 'THIS_YEAR' ]

Now, you can display it using *ngFor directive.

Answer №4

Implement the following code snippet within your component:

const availableDateRanges = Object.keys(DateRange).map(key => DateRange[key]);
const defaultSelectedDateRange: DateRange = availableDateRanges[0];

Next, embed it in your template like so:

<mat-form-field> 
    <mat-select placeholder="Select Date Range" [(value)]="defaultSelectedDateRange">
        <mat-option *ngFor="let range of availableDateRanges" [value]="range">
            {{ range }}
        </mat-option>
    </mat-select>
</mat-form-field> 

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

The Google Maps feature encountered an error (ReferenceError: google is not defined)

Utilizing the Google Maps API on my website to display multiple locations has been successful so far. However, an issue arises when attempting to determine the distance between two sets of latitude and longitude coordinates - resulting in an error message ...

What is the best way to include a search bar within a dropdown menu?

I have successfully used a dropdown feature with data display through *ngFor. Now, I am looking to incorporate a search bar into the dropdown functionality. https://i.sstatic.net/NR38T.png Here is the HTML code snippet: <ion-select item-end> ...

Instructions for incorporating a TypeScript type into a Prisma model

I am trying to incorporate a Type Board into one of my Prisma models. However, I am encountering an error stating that "Type 'Board' is neither a built-in type, nor refers to another model, custom type, or enum." Can someone provide guidance on h ...

The kendo-chart-tooltip script is causing an error by generating an Uncaught TypeError: background.isDark is not a recognized function

Click here for image descriptionHaving issues with the kendo-chart-tooltip functionality in my Angular 5 platform. The console shows a script error related to 'background.isDark' not being a function. zone.js:192 Uncaught TypeError: back ...

retrieving information from an array nested within a JSON object in an Angular application

I am struggling to retrieve two specific values from a JSON object. The content of the JSON is as follows: [ { "type":"session_start", "properties":[ { "property":"activity&q ...

The parameter type 'IScriptEditorProps' does not accept arguments of type 'string'

After trying numerous solutions, I decided to integrate this script editor into a SharePoint site. However, when attempting to implement it, I encountered an issue with the constructor lacking arguments. Despite my efforts to troubleshoot, I have been unab ...

Disabling ion-select in Ionic 2 with Typescript

To disable an ion-select element in Angular, you can use the disabled attribute like this: <ion-item> <ion-label stacked>Property Type</ion-label> <ion-select [(ngModel)]="propType" (ionChange)="ionChanger()" di ...

Diving into Angular2 template forms: unraveling the mysteries of the reset function

After going through the template forms tutorial in Angular2, I'm facing a bit of confusion regarding the behavior of the native reset JavaScript function on Angular2 ngModel. While it's not explicitly clarified in the official documentation, my u ...

Using Ngrx with Angular

When I call dispatch, the data isn't being stored properly. It might be a simple mistake, but as a beginner, I'm having trouble finding it. This is my store setup - User is an interface I created in another file: import { Action } from '@ng ...

Is there a compatibility issue between Nativescript and Angular Universal?

I am fairly new to Nativescript and recently attempted to incorporate Angular Universal building into an existing Angular 9/Nativescript application. However, I encountered the following error: [error] Error: Schematic "universal" not found in collect ...

Can you retrieve the Angular Service Instance beyond the scope of an angular component?

Is it possible to obtain the reference of an Injectable Angular service within a generic class without including it in the constructor? I am exploring different methods to access the Service reference. For example: export class Utils { getData(): string ...

How can I assign the output of a function to a variable within a class in Angular?

Is there a way for the Army class to automatically update its CP property with the sum of CP values from all Detachments in the Detachment class? In the Army class, the CP property should reflect the total CP value from all Detachments and be accessible t ...

Filtering a key-value pair from an array of objects using Typescript

I am working with an array of objects containing elements such as position, name, and weight. const elements = [{ position: 3, name: "Lithium", weight: 6.941, ... },{ position: 5, name: "Boron", weight: 10.811, ... }, { position: 6, name: "Carbon", weight: ...

Angular does not support custom validation as effectively as other frameworks

I am encountering an issue with my Angular form builder where I cannot determine the type of a file after reading it in my custom validation. Here is the link to the code on StackBlitz: https://stackblitz.com/edit/angular-ivy-atwqqc?file=src%2Fapp%2Fapp. ...

Typescript: Select just one option from the union

There is a specific Query type that contains the getBankAccounts property: export type Query = { getBankAccounts: GetBankAccountsResponseOrUserInputRequest, }; This property can return either a GetAccountsResponse or a UserInputRequest: export type Ge ...

Issue: Module compilation unsuccessful (from ./node_modules/css-loader/dist/cjs.js) during upgrade from Angular 11 to Angular 16

Summary: Can anyone help with a strange error I encountered while updating my Angular application? Situation: After finally updating my Angular 11 app to Angular 16, I faced several fixable errors along the way. However, one particular error is now hind ...

Top picks for ReactJS Typescript accounts

As a novice programmer, I am working on learning ReactJS/NodeJS/Typescript through project-based practice. Currently, I am developing a social media platform and have encountered an issue. I want to display different random users from my MySQL database in ...

Child component not inheriting Angular Material styles

I am experiencing an issue with the default styles of Angular Material. I have a parent dashboard component with child components named "HomeComponent" and "RegistrationComponent". The Input box and button from Angular Material work properly on the dashboa ...

Develop a custom class for importing pipes in Angular 4

Currently, I am working on creating a pipe that will replace specific keywords with the correct strings. To keep this pipe well-structured, I have decided to store my keywords and strings in another file. Below is the code snippet for reference: import { ...

"Exploring the Depths of Angular with Google Maps and Karma

After upgrading an Angular project from version 8 to 11 and updating the dependencies, I encountered an issue with compatibility. The project previously used the @agm/core package, which is not compatible with Angular 11. I replaced it with @angular/google ...