在 \*ngIf 的 Angular 8 HTML 模板中使用枚举

新手上路,请多包涵

如何在 Angular 8 模板中使用枚举?

组件.ts

 import { Component } from '@angular/core';
import { SomeEnum } from './global';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = SomeEnum.someValue;
}

组件.html

 <span *ngIf="name === SomeEnum.someValue">This has some value</value>

这目前不起作用,因为模板没有引用 SomeEnum 。我该如何解决?

ERROR Error: Cannot read property 'someValue' of undefined

原文由 Ling Vu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 505
2 个回答

在 TS

 import { SomeEnum } from 'path-to-file';

public get SomeEnum() {
  return SomeEnum;
}

在 HTML 中使用

*ngIf="SomeEnum.someValue === 'abc'"


编辑:时间流逝,我们作为开发人员学到了更多,我现在使用的方法不使用 get 方法。两种解决方案都有效,只需选择您最喜欢的一种即可。

在 TS

 import { SomeEnum } from 'path-to-file';

export class ClassName {
  readonly SomeEnum = SomeEnum;
}

在 HTML 中使用

*ngIf="SomeEnum.someValue === 'abc'"

原文由 Jorge Mussato 发布,翻译遵循 CC BY-SA 4.0 许可协议

您必须先将其声明为属性:

 import { Component } from '@angular/core';
import { SomeEnum } from './global';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = SomeEnum.someValue;
  importedSomeEnum = SomeEnum;
}

然后在模板中使用它:

 <span *ngIf="name === importedSomeEnum.someValue">This has some value</span>


这是供您参考的 工作演示

原文由 SiddAjmera 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题