Are you ready to empower your NX Angular libraries with seamless translation capabilities? Look no further than Transloco — the ultimate solution for integrating multilingual support into your projects! In this guide, we’ll explore how to effortlessly integrate Transloco and infuse your NX Angular libraries with Scoped Translation magic. Get ready to elevate your library’s language game effortlessly!

Let’s Dive In
#

First things first — let’s set up our NX Workspace:

1
npx create-nx-workspace nx-with-transloco

We will use the following settings:

1
2
3
4
5
6
7
8
✔ Which stack do you want to use? · angular
✔ Integrated monorepo, or standalone project? · integrated
✔ Application name · angular-environment-variables
✔ Which bundler would you like to use? · esbuild
✔ Default stylesheet format · scss
✔ Do you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)? · No
✔ Test runner to use for end to end (E2E) tests · playwright
✔ Enable distributed caching to make your CI faster · No

Once your workspace is ready, generate a new library named lib-with-transloco.

1
nx generate @nx/angular:lib --name lib-with-transloco --directory libs/lib-with-transloco

Integrate Transloco: A Smooth Ride
#

Next, let’s integrate Transloco into your library:

1
npm i @ngneat/transloco

Craft a new class named TranslocoHttpLoader within nx-with-transloco/src/transloco-http.loader.ts and fill it with the provided code snippet.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { inject, Injectable } from "@angular/core";
import { Translation, TranslocoLoader } from "@ngneat/transloco";
import { HttpClient } from "@angular/common/http";

@Injectable({ providedIn: 'root' })
export class TranslocoHttpLoader implements TranslocoLoader {
    private http = inject(HttpClient);

    getTranslation(lang: string) {
        return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
    }
}

Update ./src/main.ts to include Transloco configuration and loader setup. It\’s as simple as copy-pasting the provided snippet!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { importProvidersFrom, isDevMode } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { provideTransloco } from '@ngneat/transloco';
import { TranslocoHttpLoader } from './transloco-http.loader';

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(HttpClientModule),
    provideTransloco({
      config: {
        availableLangs: [
          {
            id: 'en',
            label: 'English',
          },
          {
            id: 'de',
            label: 'Deutsch',
          },
        ],
        defaultLang: 'en',
        reRenderOnLangChange: true,
        prodMode: !isDevMode(),
      },
      loader: TranslocoHttpLoader,
    }),
  ],
}).catch((err) => console.error(err));

For further informations how to install and setup transloco correctly, please see: https://ngneat.github.io/transloco/docs/getting-started/installation

Scoped Translation: Unleash the Power
#

Now, let’s infuse your library with Scoped Translation magic. Update lib-with-transloco.component.ts to include the TranslocoDirective in the imports section.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TranslocoDirective } from '@ngneat/transloco';

@Component({
  selector: 'nx-with-transloco-lib-with-transloco',
  standalone: true,
  imports: [CommonModule, TranslocoDirective],
  templateUrl: './lib-with-transloco.component.html',
  styleUrl: './lib-with-transloco.component.css',
})
export class LibWithTranslocoComponent {}

Create the language files en.json and de.json within the i18n folder under your library directory, providing respective translations.

1
2
3
4
5
6
7
8
9
en.json
{
    "helloWorld": "Hello World, nice to meet you!"
}

de.json
{
    "helloWorld": "Hallo Welt, schön, Sie kennenzulernen!"
}

Tweak the HTML of your library component to utilize a custom Transloco scope and serve translations from the JSON files.

1
2
3
<ng-container *transloco="let t; scope: 'libScope'">
    {{ t('libScope.helloWorld') }}
</ng-container>

At this step we are finished with the adjustments to our library and we are pretty much ready to go. Next we need to do some small adjustments to the project itself, which should include the library:

In the app.component.ts of the application we are adding the LibWithTranslocoComponent to our imports, so we can use it in the HTML:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@Component({
  standalone: true,
  imports: [RouterModule, LibWithTranslocoComponent],
  selector: 'nx-with-transloco-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
})
export class AppComponent {
  title = 'nx-with-transloco';
}

In the HTML Code we just add the component:

1
2
<router-outlet></router-outlet>
<nx-with-transloco-lib-with-transloco></nx-with-transloco-lib-with-transloco>

Until now, we have a library which is translated using the Transloco Translation Scope feature. But the files with the translations are not copied to the main application and do not get delivered to the customer. To copy the translation files, we are using the Angular feature to copy assets. We adjust the project.json of the main application under apps/nx-with-transloco/project.json we add the following content in the assets array:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
"targets": {
  "build": {
    ...
    "options": {
      ...
      "assets": [
        ...
        {
          "glob": "**/*",
          "input": "libs/lib-with-transloco/src/lib/i18n",
          "output": "assets/i18n/libScope"
        }
      ]
    }
  }
}

Important is, that the output directory needs to match the custom scope provided, in our case it is libScope.

At this point, our application is ready to go. If we run nx serve nx-with-transloco command, the application will be started and we can see the english translation of our library component.

We can tweak our application some bit and add two buttons for the language switch:

Add the following buttons to the app.component.html :

1
2
<button type="button" (click)="changeLanguage('en')">English</button> 
<button type="button" (click)="changeLanguage('de')">Deutsch</button>

And to execute the language switch, we adjust the TypeScript and add the following content:

1
2
3
4
5
6
constructor(private translocoService: TranslocoService) {
}

public changeLanguage(lang: string): void {
  this.translocoService.setActiveLang(lang);
}

Now we are ready to go, when lunching the application, we can see the translated library component and can switch between the languages we’ve defined to support.

Conclusion: Elevate Your Library’s Language Experience
#

With Transloco, integrating translations into your NX Angular libraries has never been easier. Follow these simple steps to enrich your library with multilingual support effortlessly. For the complete code, check out the GitHub repository linked below.

Get ready to create, translate, and inspire — your library is about to speak the world’s languages with ease!


Find the complete code on GitHub: https://github.com/schroedermarius/medium-nx-with-transloco

If you found this guide helpful, don’t forget to share it with fellow developers. Stay tuned for more insights and tutorials — the language revolution awaits!