Angular2 use enum value in html value attribute Angular2 use enum value in html value attribute angular angular

Angular2 use enum value in html value attribute


Your template can only access member variables of its component class. So, if you want to use the enum's values, assign it (the Enum) to a member variable.

In your component,

export class MyComp {  MyEnum = MyEnum;  .....}   

Then you're free to access the elements of the enum in your template.


You can use a enum to assign to html element as below

@Component({  selector: 'my-app',  template: `    <div>      <h2>Hello {{name}}</h2>      <input type="text" [(ngModel)]="value"/>    </div>  `,})export class App {  name:string;  myValue:any= MyEnum;  value:string;  constructor() {    this.name = 'Angular2';    this.value=this.myValue[1];    console.log(this.value);  }}

Since you are using [(ngModel)] on input element, you cannot assign to [value] property of input element.

LIVE DEMO


With Angular 2//enum

export enum IType{Vegitable=0,Fruits=1,Fish=2}

// angular 2 Component in type script

import {IType} from '/itype';export class DataComponent{getType(id:number):any{      return IType[id];}}

// in your html file

<div>{{getType(1)}}</div>