Using Different Language Files for the Same Language in Angular

Currently, I am utilizing Angular 5 for my project. All i18n translation files are conveniently stored in a single folder by default.

https://i.sstatic.net/er0wl.png

An issue has arisen where I require the use of a "basic" translation file from another project. Additionally, I wish to include a second translation file to accommodate any new translations that arise during development. Something along these lines:

https://i.sstatic.net/OGOhh.png

I am wondering if it is possible to have multiple language files that can be utilized for the same language?

Answer №1

To simplify your Angular internationalization process, consider utilizing Angular i18n Merge Files.

Just execute the following command:

npx ng-i18n-merge-files -f xlf

This will create merged content files in the same directory for different languages:

messages.de.xlf
messages.en.xlf
messages.fr.xlf
messages.nl.xlf
messages.pt.xlf
messages.ru.xlf

Answer №2

When working with Angular translations, they are typically loaded using a TranslateLoader that contains a getTranslation method. A common approach is to utilize a TranslateHttpLoader to retrieve translations from assets.

For example:

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json?cacheBuster=' + new Date().getTime());
}

If you need to handle translations from multiple files, you can use forkJoin requests and merge the responses into a single translation file. I have also included an example of how to modify directory paths, even though my paths remain the same for me.

export class CustomTranslateLoader implements TranslateLoader {
  constructor(private http: HttpClient, private config: { uiPath: string; libPath }
    }) {
  }

  public getTranslation(lang: string): Observable<any> {
    const uiUrl = `${this.config.uiPath}/${lang}.json`;
    const libraryUrl = `${this.config.libPath}/${lang}-map.json`;
    const suffix = '?cacheBuster=' + new Date().getTime();

    return forkJoin({
      uiTranslations: this.http.get(`${uiUrl}${suffix}`),
      libTranslations: this.http.get(`${libraryUrl}${suffix}`),
    }).pipe(
      map(response => ({...response.libTranslations, ...response.uiTranslations}))
    );
  }
}

export function HttpLoaderFactory(http: HttpClient) {
  return new CustomTranslateLoader(http, {
    uiPath: './assets/i18n',
    libPath: './assets/i18n',
  });
}

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

The react-bootstrap module does not have any members available for export

I'm looking to incorporate the npm module react-bootstrap from this link into my Layout component, following the ASP.NET Core 2.1 template client project structure. The challenge I'm facing is that the template uses a .js file extension, but I pr ...

Is there a more efficient method for invoking `emit` in Vue's Composition API from an external file?

Is there a more efficient way to access the emit function in a separate logic file? This is my current approach that is functioning well: foo.js export default (emit) => { const foo = () => { emit('bar') }; return { foo }; } When ...

Save the HTTP request to a variable and then send a separate HTTP request to the front-end

Looking to revamp the user interaction with the data displayed on the front end of my web app, which currently streams news feeds from Twitter. The current setup involves Angular sending an http request to a route in my Node backend, which then loads the r ...

Extend mat-table with 3 expanding columns and 1 clickable column

Is there a way to add different click events for specific columns of an Angular Material Table? Specifically, I would like the left column (Blue/LP) to trigger a click event that passes the LP value, while the right column triggers an expand action. Curren ...

"Enhancing Development with Visual Studio 2015: Leveraging tsconfig.json and Typescript 1.8.10

According to the Typescript wiki, with the release of Typescript 1.8, there is a significant enhancement in Visual Studio 2015 for 'Improved support for tsconfig.json' (emphasis added by me): With TypeScript 1.8, tsconfig.json files can now be ...

Avoid nesting subscriptions in Rxjs

I am working with an array of objects and I need to extract an array of IDs from it. After that, I have to make calls to 2 different APIs before closing the modal window. Below is my code snippet: from(this.alerts) .pipe(map(alert => alert._id)) ...

Custom generator designed for projects with tailored ng/nrwl versions

Unfortunately, due to various reasons, we are unable to utilize angular version 12 at this time. As a result, we do not wish to use the current versions of ng and nrwl. I have been unable to find any documentation on how to generate a project with a speci ...

Utilize Regular Expression Constant Validator in Angular 8's Reactive Formbuilder for efficient data validation requirements

Is there a way to efficiently store and reuse a Regex Validator pattern in Angular while following the DRY principle? I have a reactive formbuilder with a Regex validator pattern for ZipCode that I need to apply to multiple address forms. I'm interes ...

Unable to attach 'gridOptions' as it is not a recognized attribute of 'ag-grid-angular' component (Angular4)

I am facing an issue with my HTML code and Angular components: <ag-grid-angular [gridOptions]="gridOptions"></ag-grid-angular> My component code is as follows: import {GridOptions} from 'ag-grid'; ... export class SampleComponent ...

Limitations of Typescript's Index Signature Templates

Currently, I have some Typescript Interfaces with repeated and similar fields. Here's an example: interface Foo { person1Name: string; person1Address: string; person2Name: string; person2Address: string; category: string; department: ...

Leveraging Mermaid for angular applications

As a newcomer to Mermaid, I am attempting to integrate it into my Angular project. Placing it in my HTML has proven successful. <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.0.1/mermaid.min.js"></script> <div class="merma ...

Intermittent issue with Angular 2 encountered while following the Hero Editor tutorial on angular.io

I am encountering an occasional error in the console while following the angular.io tutorial using Mozilla Firefox. The error does not seem to impact the functionality or rendering of my application, and it only happens sporadically. If you could provide ...

If the boolean value is false, the material icon set will be colored red

My task management application requires a thumbs up/down icon to be displayed in green or red based on whether the task is completed or not. Previously, I was able to achieve this by using ngClass and applying different CSS classes to the icon. HTML: < ...

Receiving intelligent suggestions for TypeScript interfaces declared within function parameters

Here is a simple example I put together: https://i.sstatic.net/Fdtfa.png In this example, intellisense provides suggestions for the interface of the object named test in the foo function. It works perfectly and I love it! However, if you declare that in ...

Tips for configuring the _document.tsx file in Next.js for optimal performance

I found most of the code for this project in the official documentation example on utilizing styled-components: https://github.com/vercel/next.js/blob/canary/examples/with-styled-components/pages/_document.js However, the example was written in .js and I ...

The ListItemButton's onclick event does not trigger on the initial click when utilizing a custom component as its children

I am having trouble comprehending why this onclick function is influenced by the children and how it operates <ListItemButton onClick={() => onClickResult(q)}> <Typography variant="body1">{highlighted}</Typography> ...

Guide on how to create a custom response using class-validator in NestJS

Is it feasible to customize the error response generated by class-validator in NestJs? The default error message structure in NestJS looks like this: { "statusCode": 400, "error": "Bad Request", "message": [ { "target": {} ...

Experience the enhanced Angular Material 10 Date Range Picker featuring the exclusive matDatepickerFilter functionality

Is it possible to use Angular Material 10 MatDateRangeInput with matDatepickerFilter? When attempting the following: <mat-form-field appearance="outline"> <mat-label>Label</mat-label> <mat-date-range-input [formGroup]=&q ...

Is it possible to transform a tuple type into a union?

Is it possible to map a tuple's generic type to a union type? type TupleToUnion<T> = T[keyof T]; // This will include all values in the tuple const value: TupleToUnion<[7, "string"]> = 2; // This assignment should not be permitted since ...

The interfaces being used in the Redux store reducers are not properly implemented

My Redux store has been set up with 2 distinct "Slice" components. The first one is the appSlice: appSlice.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "./store"; export interface CounterState { value ...