Angular2 use enum value in html value attribute

2020-03-01 05:05发布

问题:

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

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 "Cannot read property 'FirstValue' of undefined"

Is there a way to use an enum value as the value of html attributes?

回答1:

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.



回答2:

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



回答3:

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>