Karl Johan Vallner
Karl Johan Vallner

Reputation: 4310

Using enums in Angular2 view templates

Interesting question. I need to use Angualar4 templating with enums.

Aka.

<div class="small-12 columns compliance-freq__item"
             [ngClass]="getComplianceFrequencyClasses( complianceFrequency, LicenceComplianceFrequency.QUARTERLY)"</div>

Notice the

LicenceComplianceFrequency.QUARTERLY

enum declaration as follows

export enum LicenceComplianceFrequency {
    QUARTERLY               = "QUARTERLY",
    MONTHLY                 = "MONTHLY"
}

This gives me a template error,

Cannot read property QUARTERLY of undefined.

I have tried intergrating this with the template in many ways, by modifiying the component itself.

1) still QUARTERLY of undefined error in the template

get LicenceComplianceFrequency() {
    return LicenceComplianceFrequency;
}

2) (screams that LicenceComplianceFrequency is not an exportable element of file *.ts)

import {LicenceComplianceFrequency} from '....';
public LicenceComplianceFrequency = LicenceComplianceFrequency;

Any advice?

Upvotes: 1

Views: 3866

Answers (1)

Karl Johan Vallner
Karl Johan Vallner

Reputation: 4310

Sorry, I already found the answer myself.

The following works with the template. Its not nice that I have to declare it this way and not be able to use enums globally, but of well...

Put this code in the component

import * as LicenceComplianceFrequency from '...';
public LicenceComplianceFrequency = LicenceComplianceFrequency;

And then you can use it in the template as follows

<div class="compliance__item">{{ LicenceComplianceFrequency.QUARTERLY }}</div>

Edit

In newer Angular versions, it is possible to do it like this

import {LicenceComplianceFrequency} from "../../shared/enums/licence-compliance-frequency.enum";
public LicenceComplianceFrequency = LicenceComplianceFrequency;

Using it in templates remains the same as before

<div class="compliance__item">{{ LicenceComplianceFrequency.QUARTERLY }}</div>

Upvotes: 6

Related Questions