pankaj
pankaj

Reputation: 1060

Get enum value in view using typescript and angular1.5

New to angular 1.5 & Typescript

I have a service with returns data, an array- devices.headerEntries:

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

I have a made a component 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
}

My view is 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 unable to figure out how to render enum text values for properties like Mode, state on UI.I m supposed to render data like [Id, 45] [Mode ,Unknown] [ State ,Paused] [serialnum ,1333] on the UI

Upvotes: 0

Views: 1548

Answers (1)

known-as-bmf
known-as-bmf

Reputation: 1222

Typescript enums are actually plain JS objects once transpiled:

enum Foo {
    Bar,
    Baz
}

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

You could retrieve the string you want via

StateEnum[item.value]

through a filter (see below) or pre-processing. You could check the return value (undefined if value not found in the enum) to keep values such as 45 and 123434 as is.

Example of filter:

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

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

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

and then in your template:

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

More info about TS enums here !

Upvotes: 1

Related Questions