如何在Angular 5视图中访问枚举值 [英] How to access an enum value in an Angular 5 view

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

问题描述

我目前正在我的html视图中直接引用enum int值,但是我更希望使用枚举名称来引用-例如,就像我在TypeScript代码中所做的那样

I am currently referencing the enum int value directly in my html view, but I would prefer to reference by the enum name - for example, as I do in TypeScript code

 if (this.nodeType === NodeType.HostService) {
      ...
 }

我的枚举定义为:

export enum NodeType {
    Location,
    Host,
    HostAccessPoint,
    HostStorage,
    HostService
}

在我的html视图中,我正在模态中加载特定的组件(包括反应形式),如下所示-所有这些都取决于enum值:

and in my html view, I'm loading specific components (which include reactive forms) within a modal as follows - and it all depends up on the enum value:

<div class="modal-body">
      <config-edit-storage-node *ngIf="selectedNode && selectedNodeTypeEnum===3" 
                        [node]="selectedNode" [nodeType]="selectedNodeTypeEnum" 
                        (cancelEdit)="cancelEdit()" (saveEdit)="onSaveEdit($event)">
        </config-edit-storage-node>
        
        <config-edit-service-node *ngIf="selectedNode && selectedNodeTypeEnum===4"
                        [node]="selectedNode" [nodeType]="selectedNodeTypeEnum" 
                        (cancelEdit)="cancelEdit()" (saveEdit)="onSaveEdit($event)">
        </config-edit-service-node>
        
</div>

在我的组件中,设置 that.selectedNodeTypeEnum :

export class ConfigNetworkTreeComponent implements OnInit {

  selectedNode: INode;
  selectedNodeTypeEnum: NodeType = null;
  selectedNodeTypeStr: string;
  
  setNodeEvents() {
   let selectedObj = that.getSelectedNode(nodeID);        
   that.selectedNode = selectedObj['selectedNode'];						
   that.selectedNodeTypeStr = selectedObj['nodeType'];
   that.selectedNodeTypeEnum = NodeType[that.selectedNodeTypeStr];
  
  }
  ...
}

最重要的是,我宁愿在html中使用这种编码风格:

Bottom line is that I would rather use this style of coding in the html:

*ngIf="selectedNode && selectedNodeTypeEnum===NodeType.HostService"

而不是引用枚举值本身.

as opposed to referencing the enum int vaue itself.

可以做到吗?

感谢和问候.

推荐答案

由于表达式上下文模板的是组件实例,您应该将NodeType枚举分配给组件类的属性以使其在模板中可用:

Since the expression context of the template is the component instance, you should assign the NodeType enum to a property of the component class to make it available in the template:

export class ConfigNetworkTreeComponent {
  public NodeTypeEnum = NodeType;  // Note: use the = operator
  ...
}

然后您可以在模板中使用该属性来引用NodeType值:

You can then use that property in the template to refer to NodeType values:

*ngIf="selectedNode && selectedNodeType === NodeTypeEnum.HostService"

有关演示,请参见 此stackblitz .

See this stackblitz for a demo.

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

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