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

Develop an interface in TypeScript for intricate data structures

Displayed below is a variable that contains a collection of objects: scenes = { sky: { image: 'assets/1.jpg', points: { blue_area: { x: 1, y: 2 }, } }, blue_area: { image: & ...

Updating reactive form fields with patched observable data in Angular

Struggling with initializing a reactive form in my component's onInit() method, as well as handling data from a service to update or create entries in a MySQL table. The issue lies in using patchValue to pass the retrieved data into the form: compone ...

Modify the property of the ChildComponent by utilizing the ViewChild method

I recently started exploring Angular and I've been experimenting with ViewChild and ViewChildren. In one scenario, I have a property called today = new Date() in my Component2. I'm accessing this property in Component1 using ViewChild and continu ...

Creating an array of objects data is a breeze with Vue.js

I have an array of data containing selected items, and I need to extract the IDs from this array into a new array so that I can send only the IDs to the back-end. Sample Code method toggleSelection(rows) { console.log('this.multipleSelection : &a ...

Resolving a persistent AngularJS 1 constant problem with Typescript

I'm currently developing an application using TypeScript and AngularJS 1, and I've encountered a problem while trying to create a constant and passing it to another class. The constant in question is as follows: module app{ export class A ...

What is the best way to bundle a TypeScript package along with its dependencies for seamless integration with various Next.js projects on a local environment

Currently, I am immersed in a project with the following arrangement: / # repository root /core # A local, unpublished npm package used by both projectA and projectB /projectA # A Next.js app /projectB # Another Next.js app In my setup, I gene ...

Linking children to their parents in a mat tree structure

I'm looking to create a mat tree based on the provided diagram. So far, I've managed to design the icons and boxes, but I'm struggling with drawing the connecting lines. Can anyone assist me with this part? I'm using a mat nested tree ...

Can you tell me about the interface type format used in the angular cli?

I found myself feeling disoriented while reading the documentation. ng generate interface <name> <type> There was ambiguity on what to input for the type field. Is it supposed to be a string, object, array, or can I define properties like ema ...

Implementing Azure Active Directory Authentication for Angular 4 or Angular 2 - Retrieving Access Tokens

I'm in the process of authenticating an Angular 4/Angular 2 app with Azure Active Directory to obtain a token code for passing as a Bearer token when calling a REST API. For this purpose, I've utilized 'ng2-adal' available at https://g ...

What is the most effective way to retrieve the width and height of an oversized image in Angular?

After attempting to retrieve the image width using the ngAfterViewInit method, a result of width = 0 is returned due to the large size of the image. Is there a way to accurately determine the image width without relying on a setTimeout() function? For re ...

Unable to create property within array in model

I am facing an issue while trying to access the name property of an array called Model[] generated from my Model.ts file. When attempting to use it in my app.component, I receive an error stating that the property 'name' does not exist on type Mo ...

Clicking on an element- how can I find the nearest element?

Encountering an issue with my next js app where I am attempting to assign a class to an element upon clicking a button. The problem arises when trying to access the next div using the following code snippet: console.log(e.target.closest('.request_quot ...

Guide on validating multiple preselected checkboxes using Angular 8 reactive forms

I have a problem with validating checkboxes in my Angular application. The checkboxes are generated dynamically from an array using ngFor loop, and I want to make sure that at least one checkbox is selected before the form can be submitted. The validatio ...

What is the most effective way to sort a list using Angular2 pipes?

I'm currently working with TypeScript and Angular2. I've developed a custom pipe to filter a list of results, but now I need to figure out how to sort that list alphabetically or in some other specific way. Can anyone provide guidance on how to a ...

Is there a different approach available since the array function "some" does not restrict type even when a type predicate is implemented?

It is expected that when using the array function "some" along with a type predicate and return statement, the TypeScript compiler would narrow down the type of dashArray. Is it reasonable to expect this behavior from the TypeScript compiler or am I incor ...

Switching from callback to function in TypeScript

Currently, I am utilizing the mongodb driver to establish a connection with mongo: public listUsers(filterSurname?:string):any { if (this.connected) { debug.log(this.db); var results; this.db.collection(' ...

Angular: Template parsing errors: Parser Error: Unexpected token "=" at column

I've been working on an Angular app created with Angular CLI and encountered unexpected token errors with the new template parser. The error messages from Angular look like this: **ERROR in Template parse errors**: Parser Error: Unexpected token ) a ...

Unlock the Full Potential of TypeScript: Seamless Export of Classes and Functions

In my AngularJS project, I have a separate JavaScript file where I declare prototype functions. Here's an example: function lastConv(){ this.item1="2" this.message="hello" ...... } lastConv.prototype.setupfromThread(data) { this.currentBox = dat ...

Angular - Jest can manage the importing of the main entry point

Currently, I am attempting to create a simple test for a component that utilizes rete.js. However, the test is failing due to difficulty handling one of the required import paths. Component import { Component, ElementRef, Injector, ViewChild } from ' ...

Incorporate FontAwesome icons into table headers within an Angular framework

I am attempting to customize the icons for sorting in my table headers by following the guidelines laid out in the ng-bootstrap table tutorial. The NgbdSortableHeader directive plays a key role in changing the sorting of columns: @Directive({ selector: ...