How can I showcase the name of a Typescript enum in an Aurelia binding?

Let's simplify things (assuming all includes and imports are correctly referenced).

Imagine you have a bindable variable of type Color on your view model (file.ts):

@bindable color: Color = Color.Green;

... and now you want to display it on the view (file.html):

<input type="text" value.to-view="color"></string-editor>

where Color is an enum defined like this (Color.ts):

export enum Color {
    Red, Green, Blue
}

This will show the numerical value of the enum in the textbox, as shown here:

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

If you wish to display the name of the enum value instead, like this:

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

You have two options...

1) Utilize a value converter

// enum-name-value-converter.ts
import { Color } from "color";

export class EnumNameValueConverter {

    toView(value) {
        return Color[value];
    }
}

... and then use it in the view like this:

// file.html
<template>
    <require from="enum-name-value-converter"></require>

    <input type="text" value.to-view="color | enumName"></string-editor>
</template>

2) Make the enum accessible to the binding context using viewEngineHooks:

// enum-binder.ts
import { View, viewEngineHooks } from 'aurelia-framework';
import { Color } from 'color';

@viewEngineHooks
export class EnumBinder {

    beforeBind(view: View) {

        view.overrideContext["Color"] = Color;

    }
}

... and then utilize it like this in the view:

// file.html
<template>
    <require from="enum-binder"></require>

    <input type="text" value.to-view="Color[color]"></string-editor>
</template>

Now for the question...

Is there a third alternative to achieve this? Is there a preferred or recommended approach?

Answer №1

By utilizing a string enum, you can easily loop through the keys or values based on your specific requirements.

enum Color {
    Red = 'Red',
    Green = 'Green',
    Blue = 'Blue'
}

To access the keys, use Object.keys.

let keys = Object.keys(Color);

And to retrieve the values:

let values = keys.map(k => Color[k]);

An example demonstrating this functionality can be viewed here.

Answer №2

What are your thoughts on assigning string values to enums like this:

export enum Color {
    Red = 'Red',
    Green = 'Green',
    Blue = 'Blue'
}

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

What is the correct way to utilize Array.reduce with Typescript?

My current approach looks something like this: [].reduce<GenericType>( (acc, { value, status, time }) => { if (time) { return { ...acc, bestValue: valu ...

Aggregate the values in an array and organize them into an object based on their frequency

I have an array of information structured like this: 0: { first: "sea", second: "deniz", languageId: "English-Turkish"} 1: { first: "play", second: "oynamak", languageId: "English-Turkish&qu ...

Although the Jest tests are passing successfully, it seems that the --covering option is not detecting all

Issue summary: I have encountered an issue with Jest while trying to generate test coverage for my TypeScript class. Even though my two tests are passing, Jest seems to be unable to pick up the covered files when using the --coverage option. The output I ...

Angular does not propagate validation to custom form control ng-select

In my Angular 9 application, I am utilizing Reactive Forms with a Custom Form Control. I have enclosed my ng-select control within the Custom Form Control. However, I am facing an issue with validation. Even though I have set the formControl to be requir ...

The type 'Observable<boolean>' cannot be assigned to type 'Observable<UserRegistration>'

function completeRegistration(email: string, password: string, firstName: string, lastName: string, location: string): Observable<UserDetails> { let body = JSON.stringify({ email, password, firstName, lastName,location }); let headers = new H ...

Unlock the potential of ng-for to dynamically generate input boxes and checkboxes!

In this Angular application, my requirement is to repeat the elements inside a div based on the number entered in an input box (record.accountRoles). <!-- Input Box --> <div class="form-group"> <label for="name">Enter the number of a ...

Tips for fixing the error message "unable to access property 'property-name' of null"

I need assistance with retrieving data from a firebase database and storing it in an array using typescript. Below is the code snippet I am working with: export class ViewUserPage { public list = []; public ref = firebase.database().ref(); public ...

Is there a way for me to verify that the key of one object is a subset of the keys of another object?

export const masterKeysObject = { MAIN: 'main', REDIRECT: 'redirect', DASHBOARD: 'dashboard', USER_ID_PARAM: ':userId', CREATE_NEW: 'create_new' } as const; type MasterKeys = keyof type ...

Can you explain the distinction between inheritance and union types in regards to portraying polymorphism?

Exploring union types in Typescript, I have discovered a new way to showcase polymorphism without relying on inheritance. In my previous Java background, I would typically approach it like this: interface Emotion { display(): string; } class Joy impleme ...

Having issues with my custom NextJS server implementation using TypeScript

I am currently exploring the use of a custom server with NextJS in conjunction with TypeScript. In order to do this, I must utilize the nextjs createServer function. Everything is functioning correctly when using the require syntax: const next=require(&ap ...

Typescript compiler reconciles with npm linked node packages

Encountering an Issue: I am facing errors when performing type checking on my application using tsc, particularly with modules connected via npm link. Below is the command I use for type-checking: "type-check": "tsc --noEmit -p tsconfig.json" and here ...

Avoid generating file modifications due to a version update when using OpenApiGenerator

When utilizing the typescript-rxjs generator, the issue arises when generating a new version of API clients. The majority of files are altered due to a simple version change: * The version of the OpenAPI document: 1.47.0-rc.20. This results in real change ...

Receiving an unexpected value from the input attribute

Currently, I am facing a challenge in retrieving data from another component by using the selector in the HTML file of the parent component. Here is how I implemented it: <app-graphs [module]="module" hidden></app-graphs> In the chi ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...

How to retrieve the value of a dynamically added textbox using Angular

While working with input elements in Angular, I noticed that they did not automatically come with a value property or any other properties unless manually added. Even after setting the value property manually, it would not update accordingly. Attempting to ...

The input '{ data: InvitedUser[]; "": any; }' does not match the expected type 'Element'

I'm currently facing a typescript dilemma that requires some assistance. In my project, I have a parent component that passes an array of results to a child component for mapping and displaying the information. Parent Component: import { Table } fr ...

What are the benefits of using material-ui@next without the need for

Thinking about creating a project using material-ui@next, but trying to avoid using withStyles. However, encountering issues with the draft of TypeScript that includes the decorator @withStyles. This leads to one question - is it possible to use material ...

Trouble implementing array filter in React component is a common issue

Hello everyone! I'm facing an issue with deleting an element from my useState array. I have the index of the element that I want to remove, and I've tried the following code snippet: const updatedArray = myArray.filter((item: any, index: number) ...

Expanding Material UI functionality across various packages within a monorepository

Currently, I am using lerna to develop multiple UI packages. In my project, I am enhancing @material-ui/styles within package a by incorporating additional palette and typography definitions. Although I have successfully integrated the new types in packag ...

What is the method to access a component from a module that has been imported into the app module?

We are currently working on a project that has the following hierarchy. app/ ├── app.component.html ├── app.component.ts ├── app.module.ts <--moduleA and moduleB is imported here ├── app-routing.module.ts ├── moduleA/ ...