Home > OS >  Enumerations use in Angular HTML
Enumerations use in Angular HTML

Time:05-11

I have an enum and would like to use it in an Angular 13 component.

Enum:

export enum PropertyCode {
  ALPHA = 'ALPHA',
  BETA = 'BETA',
  ZETA = 'ZETA',
}

TS:

import { Component, VERSION } from '@angular/core';
import { PropertyCode } from './property-code';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {

  isHidden(code: PropertyCode): boolean {
    switch (code) {
      case PropertyCode.ALPHA:        return false;
      case PropertyCode.BETA:        return true;
      case PropertyCode.ZETA:        return false;
    }
  }
}

HTML:

<ul>
  <li *ngIf="!isHidden(PropertyCode.ALPHA)">Alpha</li>
  <li *ngIf="!isHidden(PropertyCode.BETA)">Beta</li>
  <li *ngIf="!isHidden(PropertyCode.ZETA)">Zeta</li>
</ul>

Result:

enter image description here

Sandbox here

However, I don't want to create a property corresponding to that enum in the component...

It has any meaning for me, because there is no specific information to keep in, and I would like to use the UpperCase letter in the HTML, as the normal enum.

So I tried the decorator

import { PropertyCode } from './property-code';

export function PropertyCodeAware(constructor: Function) {
  constructor.prototype.PropertyCode = PropertyCode;
}

and decorated the component, but that does not seem to help

@PropertyCodeAware
export class AppComponent {

CodePudding user response:

Genially simple solution proposed by Jorge Mussato, in the .component.ts

public get PropertyCode() {
  return PropertyCode; 
}

No need of decorators (to remove)

CodePudding user response:

You have to create property in your AppComponent

propertyCode = PropertyCode;

than you can use it in your app.component.html template

<ul>
  <li *ngIf="!isHidden(propertyCode.ALPHA)">Alpha</li>
  <li *ngIf="!isHidden(propertyCode.BETA)">Beta</li>
  <li *ngIf="!isHidden(propertyCode.ZETA)">Zeta</li>
</ul>
  • Related