Angular2 use enum value in html value attribute

前端 未结 3 1842
花落未央
花落未央 2020-12-31 00:58

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

export enum MyEnum {
    FirstValue,
    SecondValue
}
export function MyEn         


        
相关标签:
3条回答
  • 2020-12-31 01:14

    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.

    0 讨论(0)
  • 2020-12-31 01:26

    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>
    
    0 讨论(0)
  • 2020-12-31 01:31

    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

    0 讨论(0)
提交回复
热议问题