Using an Angular string enum as a parameter - a guide on how to correctly reference it in

I have defined a string enum and a method within my component:

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

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

Next, I want to invoke this method in the view:

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

However, when I attempt to build using ng build --prod, an error is triggered:

An argument of type '"en"' cannot be assigned to a parameter of type 'Language'.

I understand that the correct way to call it in the component would be:

setLang( Language.en) but

how can I invoke setLang in the view?

UPDATE

In general, I am not very keen on passing a reference of my enum to a property class, so perhaps a different approach could be better:

type LangKeys = keyof typeof  Language;

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

foo('en')

Answer №1

If you want to achieve that functionality, consider the following:

Component TypeScript

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 {

  // Keep 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>

I hope this solution proves useful!

Answer №2

To easily switch between languages in your Component Class, you can add a language property:

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

...

selectedLanguage = Language

setLanguage(lang: Language.en | Language.fr) {
  const currentLang = Language[lang]
}

In your template, implement the language switch like this:

<button (click)="setLanguage(selectedLanguage.en)">

Answer №3

Present the enum as a component property:

currentLang: Language;
Language = Language;

chooseLanguage(language: Language) {
  this.currentLang = language;
}

and in the template:

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

Alternatively, opt for a union type instead of an enum:

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

chooseLanguage(language: Language) {
  this.currentLang = language;
}

and in the template:

(click)="chooseLanguage('en')"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The width of table cells expands even when using the box-sizing property set to border-box

Whenever I click the View button, I want to apply padding to the cells in my table. However, this action also increases the width of the cell. Despite researching various solutions like those found in this question, this one, and this post, I still encount ...

Utilize the up and down arrow keys to scroll through a description list in React

If you want to navigate through the list of Description Details using the tab and shift tab keys, it can be done easily. The default behavior allows for smooth navigation. <dl> <dt style={{ textAlign: "center" }}>Beast of Bodmin< ...

Angular 10 and Typescript: Variables assigned within the change event become undefined

In my code, I initialize an Algolia input and set an onchange event to it. This initialization takes place in a service. algolia_data; random_var; this.http.post<any>('APIENDPOINT', formData).subscribe(data => { instance = places({ ...

Angular and Spring setup not showing data despite enabling Cross Origin Support

I'm currently in the process of developing a full stack application using Spring and Angular. After successfully setting up my REST APIs which are functioning properly on port 8080, I encountered an issue when trying to access them from my frontend ( ...

Ways to automatically select a radio button in Angular without using NgModel

I have been reviewing all the questions here and came across one about selecting a radio button by default without using ngModel. <input type="radio" formControlName="calculate" value="1"> <input type="radio" ...

Navigate in Angular to the server but add token headers using an interceptor

I need to incorporate authenticated file serving from the backend into my Angular routing: { path: 'files/:id/:name', pathMatch: 'full', ??? } My HTTP interceptor is already set up to include token headers in other requests. What I wan ...

The art of binding styles and classes in code

What is the advantage of using style binding and class binding in Angular compared to directly using HTML style and traditional class attributes? <img src="link_img" [style.width]="imgWidth"> over <img src="link_img" width="200"> Looking fo ...

Angular 2 does not include Bootstrap CSS by default

Found this helpful tip at https://angular.io/docs/ts/latest/guide/forms.html Time to include the stylesheet you need. Go to your application's root folder in the terminal and run this command: npm install bootstrap --save In index.html, make sure ...

Exploring the issue of nested subscriptions causing bugs in Angular

My current challenge involves nesting subscriptions within "subscribe" due to the dependency of some data on the response of the previous subscription. This data flows down the subscription chain until it is stored in an array. Starting with an array of I ...

Could one retrieve the value of a type and save it as a constant?

Can I achieve something similar to this: type YesType = true; const myVar = GetTypeValue<YesType>(); // In this instance, the value true is assigned Is it feasible to assign other fixed values to constant variables like in C++? ...

How to Retrieve a File Using Angular 2

Currently, I am trying to download a file in pdf format using Angular 2. For this purpose, I have incorporated FileSaver.js to facilitate the saving of the file as a pdf. (response) => { var mediaType = 'application/pdf'; let pdfConte ...

The types definition for OpenSeadragon is lacking a property

I have developed an application using React Typescript and have integrated OpenSeadragon () for displaying images. To incorporate type definitions for OpenSeadragon, I am utilizing @types/openseadragon: https://www.npmjs.com/package/@types/openseadragon M ...

The React state remains stagnant and does not receive any updates

Although there have been numerous questions on this topic before, each one seems to be unique and I haven't found a close match to my specific issue. In my scenario, I have a grid containing draggable ItemComponents. When an item is selected, additio ...

Why does Primeng Lazy loading trigger multiple times when updating the sortField and sortOrder?

Lazyload has been successfully integrated into my primeng-table, <p-table #dataTable [columns]="tableHeader" [value]="tableData" [rows]="10" [paginator]="true" [rowsPerPageOptions]="rowsPerPage" [totalRe ...

The firebase-generated observable is causing the notorious differ error as it is not iterable

Hey there, I'm encountering an issue that's preventing the route from rendering correctly. I initially thought that unwrapping an observable into an iterable using the async pipe would solve it, but this error indicates otherwise. Sometimes obser ...

Selecting the checkbox to populate the input field

In my application, there is an input field that can be filled either by searching for an item or by clicking on a checkbox. When the user clicks on the checkbox, the input should be automatically filled with the default value valueText. How can I detect ...

What causes TS2322 to only appear in specific situations for me?

I have been trying to create HTML documentation for my TypeScript project using Typedoc. Within one of the many files, there is a snippet of code: public doSomething(val: number | undefined | null | string): string | undefined | null { if (val === null ...

ES7 Map JSON introduces a new feature by using square brackets

Currently, I am utilizing core-js for the Map collection because it appears that ES7 Map includes a Map to JSON feature that is absent in ES6 Map. (ES6): JSON.stringify(new Map().set('myKey1', 'val123').set('myKey2', 'va ...

In the realm of Typescript Angular, transferring the value of an object's property to another property within the

I'm working with a large TypeScript object and I am hoping to automate certain parts of it to streamline my workflow. myObject = [ { id: 0, price: 100, isBought: false, click: () => this.buyItem(100, 0) } buyItem (it ...

Avoid stopping Bootstrap Vue's events

Need help with a b-form-select control in Bootstrap Vue. Trying to execute a function when the value changes, but want the option to cancel the event and keep the original value. Complicating matters, the select is in a child component while the function ...