简体   繁体   中英

How to use an enum in an Angular Component

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;

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>

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?

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

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>

You can define a method or getter and compare your current state value with the enum already imported. Like this:

import { State } from "../models/state-enum.ts";

@Component({
  ....
})
export class AbcComponent implements OnInit {
  private state: State = State.init;
  ...
  get isView() {
    return this.state === State.view;
  }
}

template.html

<div *ngIf="isView">Oh is view!</div>

You could also use declaration merging to make the enum available as a static member of the component.

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

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

and then access it in the template from the constructor field

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM