Guide on converting enums in Angular 6

I have been working on translating enums in Angular, but I'm facing a challenge. While I can read and display them in a dropdown menu, translating them is proving to be difficult.

Here is an example of my code:

export enum test {
 test1 = '1 - do something',
 test2 = '2 - do anything',
}

This is how I retrieve the data:

public getEnum: any = {};

public ngOnInit(): void {
Object.values(test).map(a: string) => {

const id = a.substr(0, 5);
this.getEnum[id] = a;
}

In my HTML file, I use:

 [options]="getEnum"

For translation purposes, I need something like this:

"dropdown": {
  "doSomething": {
    "test1": "1 - do something"
   }
}

Answer №1

Here is a slightly different approach that I suggest: Instead of translating directly, store the keys in an enum in a translation.json file like this:

export enum Test {
 test1 = 'dropdown.doSomething.test1',
 test2 = 'dropdown.doSomething.test2',
}

In this way, the enum will not be dependent on the current language, allowing for easy translation of values from the enum using the following method:

const enTranslations = {
  dropdown: {
    doSomething: {
     test1: "1 - do something"
    }
  }
};

const getTranslatedText = (translations, keys: string[]) => keys.reduce((acc, curr) => acc[curr], translations);

const key1 = Test.test1
const translatedEnText = getTranslatedText(enTranslations, key1.split('.'));

You can then display the translatedEnText, or pass it into a function call where

translatedEnText === '1 - do something'
.

If you need the same key's text in different languages, simply use the getTranslatedText function with another translation object such as deTranslations.

To map your enum into an object with the same keys and translated values, you can follow this example:

const testEng = Object.values(Test).reduce((acc, key) => ({ ...acc, [key]: getTranslatedText(enTranslations, key.split('.'))}), {})

The reduce function will start with an empty object {} as acc, adding the translated text from

getTranslatedText(enTranslations, key.split('.'))
as the value under the key key on each iteration.

Playground

Answer №2

I have just finished developing a custom pipe that integrates with the translation service.

import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Pipe({
  name: 'translateEnum'
})
export class TranslateEnumPipe implements PipeTransform {
  constructor(private translate: TranslateService) {}

  transform(value: string, enumName: string): string {
    return this.translate.instant(`ENUMS.${enumName}.${value}`); // Make sure it aligns with your en.json file
  }
}

You can now implement it using type = "A"

<p>{{ type | translateEnum : 'TYPE' }}</p>
// This will retrieve the value associated with the key 'ENUMS.TYPE.A'

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

Having trouble authenticating with Google using Angular, Express, and Passport due to a 'No 'Access-Control-Allow-Origin' error?

Scenario In my development project, I'm constructing a stateless application utilizing Angular, Express, and PassportJS for user authentication via Google accounts. The aim is to implement JWT tokens to maintain the application's statelessness. ...

Is there a way to show a string value stored in Java onto an Angular 8 display?

Hey there! I am just starting out with angular 8 and have a java project where I'm using JDBC to connect to my beloved MySQL database. I have some valuable data stored in a MySQL table that I access in java and store in strings (or even a list). Now, ...

Creating an array of strings using data from a separate array of objects in JavaScript/TypeScript

I want to generate a new array of strings based on an existing array of objects, with each object belonging to the Employee class and having a firstName field: assignees: Array<Employee>; options: string[]; I attempted to achieve this using the fol ...

The error message "TypeError: text is not a function" is displayed when trying to utilize the text() method from either Blob

My current dilemma revolves around the usage of functions defined in the typescript lib.dom.d.ts file within my node.js express backend that is implemented using TypeScript. Specifically, I am encountering issues with the File/Blob interfaces where a File ...

I'm looking for some information on Typescript static functions - can anyone help me

Below is the code I am currently working with: class BaseClass { // includes a static method static someMethod() { } } class ChildClass extends BaseClass{ } class AnotherClass { protected variable: BaseClass; // Works fine with type &apos ...

What is the process for configuring React on one server and springboot on a separate server?

Can you help me with the setup of the following: Web Server : I need to set up a react + typescript application using npm at Backend Server : I also need to configure a Springboot backend server at I am currently using webpack to build the react applica ...

Transferring a PDF document to a server via a POST request

I have implemented a PDF upload section for users on my website and I want to send the uploaded file to an S3 bucket through a micro-service that I have developed. However, when I try to send the file from the front-end, it seems to be coming through empty ...

Validating patterns in Angular without using a form

Seeking guidance on validating user input in Angular6 PrimeNG pInputText for a specific URL pattern, such as , possibly triggered on blur event. This particular field used to be part of a form but has since been relocated to a more complex 6-part form int ...

Assessing Directives by Injecting the Hosting Component

In my directive, I am retrieving the component instance using the inject keyword like so: export class MyDirective implements AfterViewInit { private component: MyBaseComponent = inject(MyBaseComponent); ... } MyBaseComponent serves as an abstract com ...

What is the best way to combine two responses and then convert them into a promise?

When making two calls, the firstCallData prints data fine. However, when I use + to merge the responses, it returns me the following Response. What is a better approach to achieve this task? main.ts let data = await this.processResponse(__data.Detail ...

Can you explain the meaning of `((prevState: null) => null) | null`?

Upon encountering this code snippet: import { useState } from "preact/hooks"; export default function Test() { const [state, setState] = useState(null); setState('string'); } An error is thrown: Argument of type 'string' ...

Utilizing the power of HTML5 drag and drop functionality in conjunction with Angular Material 2's md

When working with Angular Material 2 and attempting to enable reordering of list elements, I encountered an issue where the functionality works perfectly for li-tag but fails with md-list-item. Why is that? Here is a snippet of my template: <md-nav-li ...

How can I retrieve the index of an element within a 2D array using JavaScript when the array is displayed on a webpage?

https://i.stack.imgur.com/GHx9p.png I am currently working on developing an Othello game board within an HTML page using Angular. The board itself is constructed from a 2D number array which I then display using the <table> tag on the webpage. Below ...

Tips for binding a dynamically generated array in ngModel while using ngFor for looping

I am facing an issue with binding an array dynamically in my component using ngModel. While one-way binding works fine, the model does not update when I make changes or add new elements to the array. Here is the HTML section: <div class="form-group ro ...

The journey of an Angular and NGXS store application culminates in a seamless loop of store updates

Currently, I am utilizing NGXS as the store mechanism in my application. Within the store, there is a list of conditions that are displayed using the RuleEngineAddViewStepperConditionComponent component and the *ngFor directive on the UI. Each condition ha ...

We are currently moving up from NG 12 to NG 16 and encountering an issue with the package "@ng-bootstrap/ng-bootstrap" due to an incompatible peer dependency

When attempting to upgrade from Angular version 12 to version 13, we encountered some dependency errors. Following the instructions at https://update.angular.io/?v=12.0-13.0, we tried running ng update @angular/core@13 @angular/cli@13. We received the fo ...

Javascript operations for duplicating and altering arrays

In my Angular application, I am working with an array called subAgencies that is connected to a datasource. I need to implement 2-way binding on this array. Currently, I have a method in place where I copy the contents of the original array to a new one, ...

The modeless service in FeathersJS is failing to provide the correct JSON response

Could someone please explain to me how the service creation process works? I have been struggling for hours trying to receive JSON objects that do not meet my expectations. After much trial and error, I have come up with the following code for the before h ...

Does Angular 4 Bundling Include the Complete Angular Library in the Bundle?

Is it possible that when running ng build --prod in CMD, Angular gathers all JavaScript files from node_modules and generates the vendor.bundle.js? To test this theory, I decided to delete certain definitions from package.json and rebuild. Surprisingly, t ...

Unable to connect to web3 object using typescript and ethereum

Embarking on a fresh project with Angular 2 and TypeScript, I kicked things off by using the command: ng new myProject Next, I integrated web3 (for Ethereum) into the project through: npm install web3 To ensure proper integration, I included the follow ...