如何在Angular组件中使用枚举 [英] How to use an enum in an Angular Component

查看:1305
本文介绍了如何在Angular组件中使用枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Angular组件倾向于具有全局状态(或模式"),因此我正在寻找一种有效地对此进行编码的方法.我试图做的是这样:

My Angular Components tend to have a global state (or "mode") so I am looking for a way to code this efficiently. What I tried to do is this:

@Component({
      ....
})
export class AbcComponent implements OnInit {

  enum State {
    init, view, edit, create, wait
  }
  state: State = State.init;

这个想法是AbcComponent内部的函数可以通过设置 state 属性来驱动模板的操作.例如:

The idea is that the functions inside AbcComponent can drive the template's operation simply by setting the state property. For example:

<div class="col" *ngIf="state === State.view"> ... </div>

问题是枚举定义不能出现在 class 结构内.然后,如果我将其移至 class 结构之外,则该模板将不在其本地范围内.

The problem is that the enum definition cannot appear inside the class structure. And then if I move it outside the class structure then the template doesn't have it within its local scope.

是否有其他方法可以做到这一点?

Is there a different way to do this?

P.S.如果对我感兴趣的是,我有几个 boolean 属性,每个状态一个.例如, modeInit modeView 等.它可以工作,但是笨拙,因为一次只应为 true .

P.S. If it is of any interest what I have been doing is I have several boolean properties, one for each state. For example modeInit modeView etc. It works but it is clumsy because only one should be true at a time.

推荐答案

您可以在类外部定义State枚举,也可以在另一个文件中定义

You can define the State enum outside of the class, possibly in another file:

export enum State {
  init, 
  view, 
  edit, 
  create, 
  wait
}

,并将枚举分配给该类中的公共字段:

and assign the enum to a public field in the class:

import { State } from "../models/app-enums.model";

@Component({
  ....
})
export class AbcComponent implements OnInit {
  public StateEnum = State;
  public state = State.init;
  ...
}

然后可以使用该公共字段来引用模板中的枚举:

That public field can then be used to refer to the enum in the template:

<div class="col" *ngIf="state === StateEnum.view"> ... </div>

这篇关于如何在Angular组件中使用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆