How can I update a value using a specific key in Angular?

So, I have a string value that I need to pass to another function. For instance, if the string is 'eng', I want it to be converted to 'en'. I'm looking for a solution that does not involve using slice or if statements. I attempted to create an enum, but unfortunately, that did not work as expected.

ngOnInit(): void {    
this.setLocaleDateFormat(this.translateService.currentLang);
    }

 setLocaleDateFormat(language: Languages): void {
    this.dateAdapter.setLocale(language);   } 

export enum Languages {   
'eng' = 'en',   
'slk' = 'sk',   
'cze' = 'cz',
 }

Essentially, I need to pass a value and based on some criteria, change it to something else. For example, I receive 'eng' but I want to set the locale to 'en'.

Answer №1

It appears that when calling

this.translateService.currentLang
, the result will likely be 'eng'. However, there is some uncertainty around this assumption, so it's best to revisit your initial question. Instead of defining languages as an enum, consider using a constant object.

export const Languages = {
  eng: 'en',
  slk: 'sk',
  cze:  'cz',
};

setLocaleDateFormat(): void {
    this.dateAdapter.setLocale(Languages[this.translateService.currentLang]);
}

Answer №2

The kind of lingo isn't Lingo which stands for

"en" | "sk" | "cz"
, but rather keyof typeof Lingoes.

Playground

function setLanguage(locale: Lingoes) {
  console.log('setLanguage to', locale);
}

enum Lingoes {   
 'eng' = 'en',   
 'slk' = 'sk',   
 'cze' = 'cz',
}

function setLanguageDialect(lingo: keyof typeof Lingoes): void {
  setLanguage(Lingoes[lingo]);
} 

setLanguageDialect('eng');

Answer №3

Start by defining a reference object:

const languageMap = {eng: 'en', slk: 'sk', cze: 'cz'};

Next, you can implement it in your code like so:

ngOnInit(): void {    
    this.setLocaleDateFormat(languageMap[this.translateService.currentLang] || 'defaultLocale');
}

setLocaleDateFormat(lang: string): void {
    this.dateAdapter.setLocale(lang);   
} 

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

Transforming two child arrays within an object into a single array using Ramda

I am looking to transform an object into an array. The object I have is structured like this: const data = { t1: [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ], t2: [ {" ...

How to determine the presence of 'document' in Typecsript and NextJS

Incorporating NextJS means some server-side code rendering, which I can manage. However, I'm facing a challenge when trying to check for set cookies. I attempted: !!document && !!document.cookie as well as document !== undefined && ...

Can you tell me if it's a problem that I can view the application structure from the console's source window?

I have been asking around trying to find the answer to the question "what are the implications of being able to see the project structure in the source window of a browser?". Unfortunately, I have not received a satisfactory response yet, which is why I am ...

Ways to arrange objects to fill up space in a specific sequence

My HTML document contains two child HTML elements within the parent HTML. The parent HTML has a div with a class of .page, which is a large area for the children to occupy. Both children are of the same size and I need them to spawn in a specific order; fo ...

Why does VSCode open a React app in Edge instead of Chrome?

Recently, I began a new project using the react-create-app template with typescript. However, when I run npm run dev, it unexpectedly opens in the Edge browser instead of Chrome. Does anyone know how to make it open in Chrome instead? ...

What is the best way to test for errors thrown by async functions using chai or chai-as-promised?

Below is the function in question: async foo() : Promise<Object> { if(...) throw new Error } I'm wondering how I should go about testing whether the error is thrown. This is my current approach: it("checking for thrown error", asy ...

How can Angular developers properly implement token refreshing in their applications?

Recently, I've been struggling with implementing a logic in my code. I have a specific requirement: Whenever there is a signed request (signed - means it has a JWT token for authenticated users) made to the API backend, the API backend may respond w ...

The function you are trying to call is not valid... the specified type does not have any call signatures [ts 2349

Having some trouble using functions from Observable Plot example with a marimekko chart in my TypeScript project. I encountered an error on this particular line: setXz(I.map((i) => sum.get(X[i]))) The code snippet causing the issue is as follows: fu ...

How to Hide Warning Messages in Angular NPM Package for Production Environment

Seeking advice on a coding issue I'm facing. Currently, I am in the process of creating an npm package for angular / angular material, which involves implementing some checks. If a developer fails to pass a specific argument to my function, the funct ...

Angular can display text on hover based on the state shown in a <td> element

Working on an Angular 7 project, I have a <td> element where I display different colors to indicate the status of a task: Red - Indicates 'Delayed' Orange - Indicates 'In progress' Grey - Indicates 'Rejected' Cu ...

Incorporate Lodash into your Angular2 project within Visual Studio 2015

I've been attempting to incorporate the lodash dependency into my project, but I keep encountering issues during the VS2015 build process. The error message in the build output states "Build: Cannot find module 'lodash'", causing the build t ...

Tips for integrating jwt token into axios request

I am facing an issue with my backend endpoint. I can successfully retrieve a list of customers using jwt token on Postman, but when I try to fetch the list from a React app using axios get request, it fails. After reading through this question, I implemen ...

The intersection type of an array gets lost when used in the map() function

Running into an issue with my TypeScript code snippet where the mapped type is losing intersection type information inside the map(). type Foo = { foo: number }; type Bar = { bar: string }; const arr: Foo[] & Bar[] = [{ foo: 1, bar: 'bar' }] ...

What should be used in Angular 2 Reactive Forms - controls or get()?

Lately, in templates, I've come across two different approaches: myForm.controls.StartDate.value and myForm.get('StartDate').value I initially thought that 'controls' was the recommended approach moving forward. However, when r ...

Generate a Jest dummy for testing an IncomingMessage object

I am facing a challenge in writing a unit test for a function that requires an IncomingMessage as one of its parameters. I understand that it is a stream, but I am struggling to create a basic test dummy because the stream causes my tests to timeout. : T ...

Parsing a JSON array using Moment.js within a subscription function

I have a series of time entries within a data JSON array that I need to parse and format using Moment.js. The formatted data will then be stored in the this.appointmentTimes array for easy access on my view using {{appointmentTime.time}}. Here is the JSON ...

What's stopping me from using useState() to assign API data to an array?

I have a question regarding my app that makes use of the Movies API. I am making an API request and then passing the data to an array using the useState hook. Here is a snippet of my code: const App = () => { type MovieType = { rate: string, ...

Guide to Implementing Kendo-Grid in Angular 4 CLI

Having trouble using the Kendo-Grid in Angular4? You may encounter this error message: Uncaught Error: Template parse errors: 'Kunden-grid' is not a known element: 1. If 'Kunden-grid' is an Angular component, then verify that it is par ...

Unused code splitting chunk in React production build would improve performance and efficiency of

When running the command npm run build, a build directory is generated with js chunks. I have observed an unfamiliar file named [number].[hash].chunk.js that does not appear in the list of entrypoints in the asset-manifest.json file. Instead, this mysteri ...

Display an API generated popup list using Vue's rendering capabilities

I'm attempting to generate a pop-up within a displayed list using custom content retrieved from an API request. Currently, my code looks like this: <template> <div class="biblio__all"> <a v-for="i in items" ...