Translate the PrimeNG menu bar module

I am looking to localize the primeNG menu bar component. I am unsure of how to handle the translation within the .ts file but I aim to fetch the translation data from a .json file.

import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { SocialAuthService, SocialUser } from 'angularx-social-login';
import { MenuItem, MessageService } from 'primeng/api';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.scss']
})
export class AdminComponent implements OnInit {

  display: boolean = true;
  socialUser: SocialUser = new SocialUser();
  items: MenuItem[] = [];

  constructor(private socialAuthService: SocialAuthService
    , private toast: MessageService, private translateService: TranslateService
    ) {
      this.items.map(item => item.label = this.translateService.instant(item.label));
     }

  ngOnInit(): void {
    this.socialAuthService.authState.subscribe(_ => {
      this.socialUser = _;
    });

    

    this.items = [
      { label: 'menu.pManagement', icon: 'pi pi-chart-line'},
      { label: 'menu.iList', icon: 'pi pi-wallet', routerLink: 'outsourcing' },
      { label: 'menu.iAnalysis, icon: 'pi pi-clock'}
    ];
  }

  addToast() {
    this.toast.add({
      severity: 'success',
      summary: 'Success',
      detail: ''
    });
  }

}

In the above code snippet, you can observe the menu bar items. My goal is to modify the label name when switching languages using a language change dropdown.

The contents of the en.json file are as follows:

{
    
"menu" : {
        "pManagement" : "Project Management",
        "iList" : "Item list",
        "iAnalysis" : "Item analysis"
    }
}

Answer №1

To implement internationalization in Angular, it is recommended to use the NGX-Translate library. More information about this library can be found here.

After incorporating NGX-Translate, you will need to assign a key within the label property, such as label: 'menu.pManagement'. Next, import the translate service into your component and update every instance of label:

import { TranslateService } from '@ngx-translate/core';
export class YourComponent {
   constructor(private translateService: TranslateService) {
     this.items.map(item => item.label = this.translateService.instant(item.label));
 }
}

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

Issue encountered while attempting to bind to formControl

I've searched through numerous solutions but still can't figure out why my code isn't working. I made sure to import ReactiveFormsModule, following the example in the Official Docs Example. Error: Can't bind to formControl since it isn ...

Even after successfully printing the value in the template, Angular continues to throw errors about undefined properties

There seems to be an issue in the featureImages section of the component.html file, causing the following error: news-section.component.ts:296 ERROR TypeError: Cannot read properties of undefined (reading 'value') at NewsSectionComponent_div_ ...

Executing HTTP requests in ngrx-effects

I'm currently working on an Angular REST application using ngrx/effects and referencing the example application available on GIT. I am facing challenges while trying to replace hardcoded JSON data in effects with data from an HTTP REST endpoint. The e ...

Tips on preloading a MongoDB document just once through code on a Node.js server with Mongoose

What is the process for preloading data in MongoDB using mongoose on a node server? I am looking to insert default data/documents into a collection in MongoDB. Is it achievable to add this data to the collection after creating the schema? ...

A method for enabling mat-spinner's entrance animation

I have recently implemented an Angular Material spinner with a disappearing animation that moves downwards before fading away. Is there a way to disable this animation? I have already tried using keyframes without success. <mat-spinner style="margin: ...

Angular Microfrontend with Module Federation captures and processes HTTP requests within the host application

I am looking for a way to capture HTTP requests from all remote sources within my host application so I can reset a timer that tracks user inactivity. All of the applications involved use Angular with Webpack Module Federation. Are there any suggestions on ...

Using TypeScript in combination with Angular for implementing CORS protocol

As I try to send a request to my REST endpoint, the following code is executed: this.http.request(path, requestOptions); The path is set to: http://localhost:8082/commty/cmng/users and the requestOptions are as follows: { headers: { user: "sdf", pas ...

Eliminating empty elements from arrays that are nested inside other arrays

I am facing a challenge with the array structure below: const obj = [ { "description": "PCS ", "children": [ null, { "name": "Son", ...

Angular 10: Module Alias Import Not Resolving in VSCode due to Path Mapping Recognition Issue

After updating a project from Angular 8.2 to version 10, I followed the instructions on https://update.angular.io/ and everything seemed fine. However, once I implemented Path Mapping, I started encountering this error everywhere: Cannot find module ' ...

Error: the function t.rgb is not defined

An error occurred: "Uncaught TypeError: t.rgb is not a function" After creating an Angular application, building it, and trying to serve it, I encountered the following issue: $ ng serve --prod --aot The error message displayed in the console is as foll ...

Angular 6 Error: 'bootbox' is Not Recognized

I have integrated bootbox into my Angular application following the guidance provided in this answer. However, upon building the project, I encountered the following error: error TS2304: Cannot find name 'bootbox'. Below is an excerpt from my ...

What is the reason for array.push not functioning properly on a collection that contains table data in Angular4 and PrimeNG?

After including the following HTML code: <p-dataTable selectionMode="single" [(selection)]="selectedUsers" dataKey="id" ...

Can you explain the significance of this line of code: elements:Array<any>?

Completely new to Angular and Javascript. I recently received an assignment for my angular.js class where I need to work on a code hint and make a simple form. The code hint provided is as follows: export class AppComponent { items:Array<any> ...

Exporting third-party types in an npm package

I recently developed an npm package that relies on types from the DefinitelyTyped repository. I added these types as devDependencies in the npm package and was able to use them without any issues, like so: export class Example { constructor (options: Ex ...

PHP Function for Capacitor 4 enables Apple Sign In stacking functionality

I'm encountering an issue with the Sign In Apple functionality on Capacitor 4. When I try to provide the password for the Apple ID, the process gets stuck like shown in the image I uploaded. The dialog prompt for the Apple ID password opens successfu ...

How to efficiently retrieve parent content from a child component

parent.html <ion-content class="project"> <ion-grid> <ion-row class="details"> <project [data]="data"></project>// this child component </ion-row> </ion-grid> </ion-content> project.ht ...

The angular 2 router is failing to navigate properly when using the history forward/backward button

The history push state feature is not working properly with the Angular 2 router in both Chrome and Firefox. The forward button never works, and the backward button only works for 2 steps before the UI stops responding to it. Here is the code I am using: ...

Transform a group of objects in Typescript into a new object with a modified structure

Struggling to figure out how to modify the return value of reduce without resorting to clunky type assertions. Take this snippet for example: const list: Array<Record<string, string | number>> = [ { resourceName: "a", usage: ...

Ways to set a button as default clicked in an Array

I have a collection that stores languages and their boolean values. My goal is to automatically set buttons to be clicked (active) for each language with a true value in the collection. Whenever a different language is selected by clicking on its respect ...

I'm having trouble with class attributes not functioning properly in TypeScript within Angular. What steps can I take to resolve this issue

Currently, I am in the process of mastering Angular, CSS (particularly Tailwind), HTML, and TypeScript as a means to construct a website. Despite clicking the menu button on the navigation bar thrice, I was puzzled why this.name appeared as undefined duri ...