2

I've got a string enum and a method in my component:

export enum Language {
    de = 'de',
    en = 'en'
}

setLang(lang: Language.en | Language.de) {
    const curent = Language[lang]
}

Than I want to call it in the view:

<button (click)="setLang('en')">

but when I run ng build --prod I've got this error

Argument of type '"en"' is not assignable to parameter of type 'Language'.

I know if I should call in the component it should be

setLang( Language.en) but

how can I call setLang in the view?

UPDATE

All in all I don't like very much passing a reference of my enum to a property class so may be this could be a better approach

type LangKeys = keyof typeof  Language;

function foo(lang:LangKeys) {
    const curent = Language[lang]
}

foo('en')
user3887366
  • 2,226
  • 4
  • 28
  • 41
  • 1
    Since you already accepted an answer i should mention that there a workaround exists. Which includes creating a pipe. That way you can use enums in views without polluting your component. See [this](https://stackoverflow.com/a/59447550/12354911) – Eldar Dec 24 '19 at 18:55

3 Answers3

3

You can do something like that:

Comonent TS

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

export enum Language {
  de = 'de',
  en = 'en'
}

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

  // Store a reference to the enum
  language = Language;

  setLang(lang: Language) {
    const current = Language[lang];
    console.log(current);
  }

}

HTML file

<button (click)="setLang(language.en)">click</button>

Hope it helps!

ic_paty
  • 432
  • 3
  • 10
2

Just create a property in your Component Class:

import { Language } from './path-to-enum-file';

...

languageEnum = Language

setLang(lang: Language.en | Language.de) {
  const curent = Language[lang]
}

And then in the template try doing this:

<button (click)="setLang(languageEnum.en)">
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
1

Expose the enum as a property of your component:

current: Language;
Language = Language;

setLang(language: Language) {
  this.current = language;
}

and in the view:

(click)="setLang(Language.en)"

Alternative: use a union type rather than en enum:

type Language = 'en' | 'de';
[...]
current: Language;

setLang(language: Language) {
  this.current = language;
}

and in the view:

(click)="setLang('en')"
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255