Making enum values available to Angular template

Let’s say you want to make some enum values available to your Angular template. Angular binding cannot reference directly the enum value. A hack to work this around consists in adding to your component class a member variable initialized with the enum type.

Ex :

import { Component, Input, OnInit } from '@angular/core';


enum TransfertNature {Gerant, Etablissement, Autre};

@Component({
  selector: 'app-transfert-siege',
  templateUrl: './transfert-siege.component.html',
  styleUrls: ['./transfert-siege.component.css']
})
export class TransfertSiegeComponent implements OnInit {

  nature: TransfertNature;

  TransfertNature: any = TransfertNature; // Can be used in the template

  constructor() { }

  ngOnInit(): void {
  }

}

The Angular template will then be able to referece any value using the variable. Ex :

  <ng-container [ngSwitch]="transfert.nature">
    <ng-container *ngSwitchCase="TransfertNature.Gerant">

Leave a Reply

Your email address will not be published. Required fields are marked *