如何在HTML中使用枚举?

时间:2018-09-12 08:35:59

标签: javascript angular

当我引用一个枚举值时,我的错误率低于错误值。

ERROR TypeError: Cannot read property 'Text' of undefined

有没有办法在组件的html部分中使用此枚举?

我的枚举;

 export enum InputType {
    Text = "text",
    Number = "number",
    Color = "color"
}

我的组件;

export class AppComponent {
  title = 'app';

  inputType : InputType;

}

html部分;

<app-input [inputType]="inputType.Text"></app-input>

1 个答案:

答案 0 :(得分:2)

更改:

export class AppComponent {
  title = 'app';

  inputType : InputType;

}

收件人:

export class AppComponent {
  title = 'app';

  inputType = InputType;

}

否则,inputType将被typescript视为InputType,但永远不会被分配,因此在运行时它将为undefined(并且angular将抛出异常如上所述,因为它试图访问未定义组件属性的属性。