How to access an enum value in an Angular 5 view

前端 未结 3 1385
我在风中等你
我在风中等你 2020-12-19 00:06

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

相关标签:
3条回答
  • 2020-12-19 00:36

    You can create a method for returning string representation of enum element in your component, like:

    getActionName(): string {
        return Action[this.action];
      }
    

    And in html template call it like:

     <button type="submit" [disabled]="!userProfileForm.valid" class="btn btn-danger">
                {{getActionName()}}</button>
    

    When your declared enum is like:

        export enum Action {
      update, create
    }
    
    0 讨论(0)
  • 2020-12-19 00:38

    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
      ...
    }
    

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

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

    See this stackblitz for a demo.

    0 讨论(0)
  • 2020-12-19 00:44

    Simplest way to use enum in HTML with intellisense

    Your enum

    export enum NodeType {
        Location,
        Host
    }
    

    Your component class

    export class YourComponent {
    
        get Node() {
           return NodeType
        }
    
    }
    

    Your component's HTML

    <div>{{Node.Location}}</div> // 0
    <span *ngIf="Node.Location == 0">Location</span>
    
    0 讨论(0)
提交回复
热议问题