Accessing enum values in a view with Typescript and AngularJS version 1.5

Recently started working with Angular 1.5 and Typescript

I have a service that returns data in an array format called devices.headerEntries:

[{name:id,value:45} ,{name:Mode,value:1},{name:State,value:2},{name:serialnum,value:123434}

I created a component structured like this

   module my.app {
'use strict';
export enum ModeEnum {
    Unknown = 0,
    Manual,
    Scheduled
}
export enum StateEnum {
  Unknown = 0,
  Playing,
  Paused,
  Stopped
}

@mmw.core.Component('my.app', 'mmwListView', {
    controllerAs: 'vm',
    bindings: {
        device: '<'
    },
    templateUrl: 'app/mydevice/mmw-listview.component.html'
})

class ListViewComponent {
    static $inject = ['$window'];

    constructor(private $window: ng.IWindowService
    ) {
    }

      public device: devices.headerEntries
}

The view looks like this

   <md-content>
 <md-list-item class="md-2-line" ng-repeat="hi in vm.device.headerEntries">

      <div class="md-list-item-text">
        <h3> {{hi.name}}</h3>
        <p> {{hi.value}}</p>
      </div>
    </md-list-item>
  </md-list>

I am struggling to display enum text values for properties like Mode, state on the UI. I need to show data like [Id, 45] [Mode, Unknown] [State, Paused] [Serial Number, 1333] on the UI

Answer №1

When Typescript enums are transpiled, they become plain JavaScript objects:

enum Foo {
    Bar,
    Baz
}

> Foo[0] = 'Bar'
> Foo[1] = 'Baz'
> Foo['Bar'] = 0
> Foo['Baz'] = 1
> Foo[8] = undefined
> Foo['Something'] = undefined

To retrieve the string you desire, you can use:

StateEnum[item.value]

This can be done through a filter (shown below) or pre-processing. By checking the return value (which is undefined if the value is not found in the enum), you can maintain values like 45 and 123434.

An example of a filter:

export class StateFilter {
    constructor() {
        return (value: number) => {
            if (value == null) { return ''; }

            return StateEnum[value] || value;
        };
    }
}

angular
    .module('app')
    .filter('stateFilter', StateFilter);

Then you can use it in your template like this:

<p>{{hi.value | stateFilter}}</p>

For more information on TypeScript enums, check out this link!

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

Stuck on loading screen with Angular 2 Testing App

Currently working on creating a test app for Angular 2, but encountering an issue where my application is continuously stuck on the "Loading..." screen. Below are the various files involved: app.component.ts: import {Component} from '@angular/core& ...

Tips for creating a webfont using SVG icons

Seeking advice on generating a webfont from SVG icons using webpack, angular2, and typescript. Any suggestions on the best way to achieve this? Struggling to find helpful information online. Please lend a hand! https://i.sstatic.net/kvClK.png The code pr ...

angular2 - Having trouble retrieving data from subject

Why am I unable to successfully initialize and retrieve data from a service using a subject in Angular? HomeComponentComponent.TS export class HomeComponentComponent implements OnInit { public homeSub; constructor( private subService: SubjectServ ...

Dynamically setting the IMG SRC attribute with the base64 result of a FileReader for file input

Looking for a little guidance on something new, I'll keep it brief because I'm sure it's just some small detail I'm overlooking... Starting with an image like this, where currentImage is the initial existing image path; <img src="{ ...

Converting an Angular promise into a jQuery deferred object: A guide

I am looking for a way to send promises from my module/sdk to non-angular JavaScript. If I return a promise to jQuery, it seems like I should use a jQuery deferred object. Is there a way to convert an Angular promise to a jQuery promise/deferred object? A ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

Does the JavaScript Amazon Cognito Identity SDK offer support for the Authorization Code Grant flow?

Is there a way to configure and utilize the Amazon Cognito Identity SDK for JavaScript in order to implement the Authorization Code Grant flow instead of the Implicit Grant flow? It appears that the SDK only supports Implicit Grant, which means that a Clie ...

Issue encountered: Model binding is not functioning properly in AngularJS and MVC4 collaboration

Recently, I delved into learning AngularJS and encountered a simple issue. I have a controller in JavaScript that showcases candidate results, and my goal is to display the specific details of each candidate. //Fetches Candidate List var Listcandidates = ...

Creating a bespoke numeric input component using React Native

As I work on developing a numericInput component, my goal is to streamline the code by eliminating RNTextInput. The part that confuses me is how it utilizes React.forwardRef<RNTextInput, Props>((props, ref) => { const { onChangeText, ...rest } ...

Creating a Search Functionality within a Tab Component in Ionic

I'm currently facing an issue with adding a search bar under the "Search" tab in my project. I've tried implementing similar logic to what's shown here, but it doesn't seem to function properly when using the ionic serve --lab live in-b ...

Using TypeScript generics to create reusable type definitions for reducers

I have a common reducer function that needs to be properly typed. Here's what I have come up with: export interface WithInvalidRows<T extends { [K in keyof T]: InvalidCell[] }> { invalidRows: T; } interface AddPayload<S extends WithInval ...

Parent Class implementation for dynamic loading of components

I have been working on creating a new code for dynamic component loading using a parent-child relationship. The child component is set to override the parent and will be used for dynamically loading components. I found this useful link that guided me throu ...

Angular Material Datatables - Issue with Paginating Data from Firestore

Data has been retrieved from Firestore and transformed into an Observable array with the InvoiceItem type. The data loads correctly onto the datatable, but there seems to be an issue initializing the paginator with the array's length. This could poss ...

The property is not found in the '{}' type but is necessary in the type... Typescript connect strategy

Hello, I am currently trying to establish a connection pattern for React with TypeScript. I have a reducer set up as follows: type State = { version: number, a?: string } interface ActionC { type: string payload?: number } type IAction = Action ...

AngularJS directive that rounds numbers to two decimal places

I am looking to develop a custom directive that rounds off two-digit values after the decimal point. For instance: 10.456456 will be rounded to 10.46 10.3633 will be rounded to 10.34 Here is my current attempt at the directive, but it seems to be ineffe ...

How come I am receiving {"readyState":1} in the DOM instead of JSON data in AngularJS?

Currently, I am facing an issue where instead of the JSON data (which consists of only 49 items) showing up on the DOM, I am getting {"readyState":1}. I believe this is just a test to ensure that my code is functioning correctly. Although I have identifie ...

Establish the predefined date for the air-datepicker

I am currently utilizing the air-datepicker inline feature. My objective is to establish the starting date for it. Below is the script detailing my attempt: export function load_datepickers_inline():void { const search_legs_0_datepicker = $("#search_leg ...

Sending two arguments to an Express Mongoose API in order to fetch a singular outcome

I'm currently exploring the world of developing APIs using Express and Mongoose. Setting up basic endpoints for get, post, put has been a breeze so far. Now, I'm eager to create an endpoint where I can pass two parameters to search a collection ...

Issue with importing MomentJS globally in TypeScript

When it comes to defining global external modules in TypeScript, there is a useful option available. For instance, if you have jQuery library loaded externally, you can set up a global definition without having to include its duplicate in the TypeScript bu ...

Ways to address the issue of Node.js versions with odd numbers not qualifying for LTS status and being unsuitable for production node:16120 due to UnhandledPromiseRejectionWarning

After attempting to initiate a new Angular application with ng new app, I encountered the following error: Node.js version v11.0.0 detected. Odd numbered Node.js versions will not enter LTS status and should not be used for production. For more information ...