Angular2 use enum value in value html attribute

I am trying to use the enum value to set the selected HTML attribute value:

export enum MyEnum { FirstValue, SecondValue } export function MyEnumAware(constructor: Function) { constructor.prototype.MyEnum = MyEnum; } @MyEnumAware @Component({ templateUrl: "./lot-edit.component.html", styleUrls: ["./lot-edit.component.css"], }) export class LotEditComponent implements OnInit { @Input() myEnumValue: MyEnum ; 

}

 <td><input name="status" type="radio" [value]="MyEnum.FirstValue" [(ngModel)]="myEnumValue"></td> <td><input name="status" type="radio" [value]="MyEnum.SecondValue" [(ngModel)]="myEnumValue"></td> 

however I get "Can't read property" FirstValue "from undefined"

Is it possible to use the enum value as the value of html attributes?

+6
enums angular typescript
Feb 26 '17 at 3:19
source share
3 answers

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

In your component

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

Then you can access the enumeration elements in the template.

+11
Feb 26 '17 at 4:42 on
source share

You can use the enumeration to assign an html element as shown 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 the [(ngModel)] element on the input element, you cannot assign the [value] property of the input element.

Live demo

+1
Feb 26 '17 at 5:05
source share

With Angular 2 // enumeration

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

// Angular 2 Script type component

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

// in your html file

 <div> {{getType(1)}} </div> 
-one
Aug 22 '17 at 7:21
source share



All Articles