30秒学会 Angular 片段 · 2018年11月5日

30秒学会 Angular 片段 – Accessing Enums in template

Enums are great but they are not visible in Angular templates by default.
With this little trick you can make them accessible.

enum Animals {
  DOG,
  CAT,
  DOLPHIN
}

@Component({
  ...
})
export class AppComponent {
  animalsEnum: typeof Animals = Animals;
}

file:app.component.ts

import { Component } from "@angular/core";

enum Animals {
  DOG,
  CAT,
  DOLPHIN
}

@Component({
  selector: "my-app",
  template: `<div *ngIf="value === animalsEnum.CAT">meow</div>`,
})
export class AppComponent {
  value: Animals = Animals.CAT;
  animalsEnum: typeof Animals = Animals;
}

翻译自:https://www.30secondsofcode.org/angular/s/accessing-enums-in-template