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

Typescript compiler: Unable to locate the definition for 'Map' data type

I am developing an Electron + Angular application. I have decided to incorporate Typescript for my Electron component, so I created a main.ts file and attempted to compile it to main.js using the 'tsc main.ts' command. Unfortunately, I encountere ...

What could be the reason for my npm package installed globally to not be able to utilize ts-node?

Recently, I've been working on developing a CLI tool for my personal use. This tool essentially parses the standard output generated by hcitool, which provides information about nearby bluetooth devices. If you're interested in checking out the ...

What prevents us from returning Observable.of(false) in the catch block within the canActivate function?

In order to protect certain routes (admin), I utilize the canActivate feature. In this scenario, I employ an authGuard class/function: The issue arises when attempting to return an observable of boolean using: return Observable.of(false);. This approach d ...

Why is an additional return statement necessary in Angular when attempting to retrieve data from a custom service?

As a newcomer to javascript and angular, I have successfully created a custom service in angular that connects to a URL and retrieves information. My goal is to return response.data instead of just the response itself. var getAlldatas = function($http) ...

Best Practices for Utilizing NPM Modules with TypeScript

I am interested in developing an npm module using TypeScript. Can anyone suggest a best practice guide on how to start? Here are my questions: Node.js does not natively support TypeScript, so what is the recommended way to publish an npm module? Shoul ...

Issues with navigation in React Native Typescript

Currently, I am in the process of developing a new React Native Expo project utilizing TypeScript. I have been attempting to configure navigation following the guidance provided in React Native's TypeScript documentation. However, upon running and sim ...

"Exploring the Power of TypeScript Types with the .bind Method

Delving into the world of generics, I've crafted a generic event class that looks something like this: export interface Listener < T > { (event: T): any; } export class EventTyped < T > { //Array of listeners private listeners: Lis ...

tsc and ts-node are disregarding the noImplicitAny setting

In my NodeJS project, I have @types/node, ts-node, and typescript installed as dev dependencies. In the tsconfig.json file, "noImplicitAny": true is set. There are three scripts in the package.json file: "start": "npm run build &am ...

Using TypeScript to define a static enum within a React functional component

Creating a React.FunctionalComponent with static props: import MyAwesomeComponent from './MyAwesomeComponent'; ... <MyAwesomeComponent mode={MyAwesomeComponent.modes.superAwesome} /> Static props defined as key-value pairs: MyAwe ...

Too many open files error encountered in Watchpack (watcher) - NextJS

Encountering an issue with watchpack resulting in the error messages shown above while running a next app using next dev. The error message is displayed continuously on the screen as follows: Watchpack Error (watcher): Error: EMFILE: too many open files, w ...

Encountering a tslint issue: "Parsing error: Expression expected"

Could someone provide some insight on this issue? Iā€™m encountering an error message that says Failed to compile. Parsing error: Expression expected with this specific line of code - isLogViewVisible: dashboard?.logView !== null where the variable isLog ...

Is it possible to register multiple mini router apps using app.use() in MEAN?

Within my node/express app.js main file, I have established a mini-app router: var router = express.Router(); I pass this router to my controller functions and then export it. Finally, I register the router by using: app.use('/Link', router); ...

Utilizing AWS Amplify with TypeScript and TypeScript Lambdas for powerful web development

Currently, I am working on a project that involves a nextjs frontend with TypeScript and AWS Amplify for the backend. My intention is to write my Lambda functions in TypeScript as well. However, I have encountered an issue where I have one tsconfig.json fi ...

What is the best way to prevent or highlight a particular row in a table depending on the line number values using Angular 2 and NgFor?

My work involves using angular2 and dealing with a table of games. I have a list of games in the database that have been clicked on before (each game can be clicked once). I want to add a class (whether it's a block or painted it doesn't matter) ...

Error thrown by webpack: Module 'pug' not found when attempting to access get-api

After setting up webpack in express, a new folder was created. When I try to run bundle.js, it shows the message "server is running on port 3000". However, when I access the API at http://localhost:3000/api/test, the whole bundle.js loads in the console an ...

Is there a technique to block small increments in a Time Input field?

Currently in the process of developing a tool to automate task scheduling within an Angular app. I am looking for a way to restrict the user's input when selecting the hour for task execution without having to install a complex input management packag ...

Retrieving radio button value in Angular 2

Currently, I am attempting to retrieve the radio button value in an Angular 2 project. The radio buttons are defined in index.html as: <input type="radio" id="options1" name="function" value="create"> <input type="radio" id="options2" name="func ...

Leverage the event handler within a React Component when working with TSX tags

Is there a way to expose an event handler that is defined within a React Component in an HTML-like tag? For example: <MyComp param1="abc" param2="def" onDoSomething={this.someMethod} /> I am trying to define the onDoSomething event, but currently I ...

Unable to serve static files when using NextJs in conjunction with Storybook

The documentation for Next.js (found here) suggests placing image file paths under the public directory. I have a component that successfully displays an image in my Next.js project, but it doesn't render properly within Storybook. The image file is ...

Encountered a snag during the construction of an Angular 8 SSR application

Currently, I am in the midst of working on an angular 8 project and my goal is to build it for production. However, each time I try running the build command, a critical error arises: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation fai ...