Skip to content

Internationalization (I18N) in Angular with Transloco

Internationalization (I18N) in Angular with Transloco

This article was written over 18 months ago and may contain information that is out of date. Some content may be relevant but please refer to the relevant official documentation or available resources for the latest information.

In this post, I'm going to talk about internationalization and how to implement it in an Angular application with the help of a neat library called Transloco.

What is Internationalization (I18N)?

I think it's best to start by explaining what internationalization (i18n for short - first letter of the word followed by the number of letters until the last letter of the word) is and why it is so important.

Internationalization is the process of adapting a software application to allow it to be easily used in multiple countries. There is a common misconception that this means that all text within an application must have translations for multiple languages; however, full i18n goes beyond just plain text in your application.

In many western countries, red is commonly used to signal danger. However, in some regions throughout the world, red is seen as a positive color.
Likewise, in many western countries, text is read from left to right; however, in some languages text is read from right to left.

Another example of where i18n comes into play is in images. If an image in your application contains text, to fully support i18n, it may be appropriate to generate multiple images each with the correct translations for the languages you support in your application. You would then need to serve the correct image depending on what country the user using your application is located in.

Naomi Meyer gave a brilliant talk on this subject at AngularConnect. You can watch that talk here if you are interested in learning more about. It's worth watching!

What is Transloco?

Transloco is a library developed and maintained by the NgNeat team. It contains a multitude of features and officially supported plugins to help make translating your Angular applications easy, maintainable, scalable and performant. It is actively maintained and it supports:

  • Lazy loading
  • Multiple fallbacks
  • Server-side rendering
  • Localization (l10n)
  • Runtime language changing
  • Multiple languages simultaneously
  • Pluralization (through an official plugin)

It's very easy to set up and use as we'll see in the next part of this post!

Integrating Transloco into an Angular Application

Now it's time to get our hands into some code! Let's start with a clean slate. I'll assume you have nodejs and npm installed already. If not, I recommend using the LTS version!

Installation

If you don't already have the Angular CLI installed globally, run the following command in your favourite shell:

npm install -g @angular/cli

This will install the Angular CLI globally. Next, we'll create a new app using the Angular CLI:

ng new transloco-test

You'll be given a few prompts. To try out the library, we don't need anything too crazy:

➜ ng new transloco-test
? Would you like to add Angular routing? No
? Which stylesheet format would you like to use? CSS

Now we'll need to navigate into the newly created transloco-test folder: cd transloco-test

From here we can use the ng add command to add Transloco to our application.
Note: By running the ng add Schematic, Transloco will automatically create files in our project to cover the initial set up process!

ng add @ngneat/transloco

After running this command we'll see some prompts from the library for the initial set up. For now, we will stick to the defaults:

? 🌍 Which languages do you need? en, es
? πŸš€ Are you working with server side rendering? No

We will also see that some files were created and updated: Ng Add Schematic Output

Let's take a quick look at these files.
tranloco.config.js - stores some basic configuration settings used by some additional Transloco tools.
src/assets/i18n/{en|es}.json - these are the files in which our translations are stored. Usually, one file per language supported. They are set up as key-value pairs, however, Transloco does support nested keys.
src/app/transloco/transloco-root.module.ts - this file sets up the Transloco module, config, transpiler and translation loader.

Let's take a closer look at this file.

@Injectable({ providedIn: "root" })
export class TranslocoHttpLoader implements TranslocoLoader {
  constructor(private http: HttpClient) {}

  getTranslation(lang: string) {
    // We can see here that the file names of our translations are important
    // They must match the available languages in our app
    return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
  }
}

@NgModule({
  exports: [TranslocoModule],
  providers: [
    {
      provide: TRANSLOCO_CONFIG,
      useValue: translocoConfig({
        // These strings of available langs must match our translation file names
        availableLangs: ["en", "es"],
        defaultLang: "en",
        // Remove this option if your application doesn't support changing language in runtime.
        reRenderOnLangChange: true,
        prodMode: environment.production,
      }),
    },
    { provide: TRANSLOCO_LOADER, useClass: TranslocoHttpLoader },
  ],
})
export class TranslocoRootModule {}

This file stores the configuration and the translation loading strategy that Transloco will use to fetch the translations for our app.
It's important to note that the filenames of our translation files must match the array of availableLangs that we support in the app.

Adding Translations to our templates

Transloco provides multiple methods for fetching translations in our templates:

  • Pipe
  • Attribute Directive
  • Structural Directive

Let's look at how to do each in turn.

First, we will set up some translations in our en.json located in our assets/i18n folder:

{
  "title": "Transloco Test",
  "welcomeText": "Hello {{ name }}"
}

Notice that welcomeText contains {{ name }}: this is a dynamic value that we pass into the translation.

We will also up es.json. You can translate this yourself if you want, I'm just going to prefix the translations with ES- to show the differentiation between the translations:

{
  "title": "ES- Transloco Test",
  "welcomeText": "ES- Hello {{ name }}"
}

Open up app.component.html and delete all the content in the file and insert the following:

<div>
  <h1>{{ 'title' | transloco }}</h1>
  <h3>{{ 'welcomeText' | transloco: {name: 'World'} }}</h3>
</div>

Now if you run the app using ng serve you should see the following:
Translated Text

Awesome! Transloco was able to find our keys and successfully fetch the correct translations for it!

We can also use an attribute directive to achieve the same result:

<div>
  <h1 transloco="title"></h1>
  <h3 transloco="welcomeText" [translocoParams]="{name: 'World'}"></h3>
</div>

I personally feel like this approach works well when you aren't providing dynamic values to the translation and are just using transloco="title". With multiple params it could get messy.

The final option for performing translations in the template is to use a structural directive. My favourite method personally.

<div *transloco="let t">
  <h1>{{ t('title') }}</h1>
  <h3>{{ t('welcomeText', {name: 'World'}) }}</h3>
</div>

All three approaches will give the same output; however, there is a performance benefit to using the structural directive approach. It only uses one subscription to update the full template during language changes and change detection cycles.

We can also get translations in your TS files if we need them:

Open app.component.ts and inject TranslocoService into the constructor.


constructor(
    private readonly translocoService: TranslocoService
){}

ngOnInit() {
    // We can then use the service to fetch translations
    const example = this.translocoService.translate('welcomeText', {
      name: 'World',
    });
}

Supporting Runtime Language Change

One of the greatest features of Transloco is that it allows you to change the language of the translations at runtime. And it's super simple to do!

Open up the app.component.ts file and create a new method:

  switchLanguage() {
    if (this.translocoService.getActiveLang() === 'en') {
      this.translocoService.setActiveLang('es');
    } else {
      this.translocoService.setActiveLang('en');
    }
  }

Now, when this method is called the translations will be changed from en to es.

Open app.component.html and add a button to toggle the language:

<div>
  <h1>{{ "title" | transloco }}</h1>
  <h3>{{ "welcomeText" | transloco: { name: "World" } }}</h3>
</div>

<button (click)="switchLanguage()">Switch Language</button>

Now, when we click on the button we should see our translations update in real-time: Language Switching

Pluralization Support

It's fantastic being able to set translations and have them rendered on screen, but what about the following scenario?

{{ numberOfSeconds }} seconds remaining

If numberOfSeconds is 1, that should read 1 second remaining but it won't. It will always render 1 seconds remaining.

That's a problem! However, Transloco has an official plugin that adds MessageFormat support.

The MessageFormat Plugin can be easily added to our app and used to support pluralization and gender in our translations.

Let's see how to add it. First, we need to install two new packages:

npm i messageformat @ngneat/transloco-messageformat

Then we need to initialize it in our TranslocoRootModule, so open transloco/transloco-root.module.ts and add the following to the imports array:

@NgModule({
  imports: [
    TranslocoMessageFormatModule.init()
  ]
  ...
})
export class TranslocoRootModule {}

And voila! Support has been added. But how do we use it?

Let's implement a {{ numOfResults }} search results translation to see it being used.

Open assets/i18n/en.json and add the following key-translation pair:

{
    ...,
    "searchResults": "{numOfResults, plural, =0 {no results found} one {1 search result} other {# search results}}"
}

Now in our app.component.html add the following below the welcome text:

<p>{{ t('searchResults', numOfResults) }}</p>

Finally, in your app.component.ts set a new property called numOfResults:

export class AppComponent {
    numOfResults = 0;

    ...
}

Change the value of numOfResults to see the translation change appropriately!

MessageFormat Support

Final Regards

Hopefully, this article shows how easy it is to implement I18N support into our Angular apps with the help of Transloco! Transloco has so many more features and plugins available to make your i18n experience even nicer.

Two that I'd like to call out are:

Translation Flattening

Transloco supports nested keys:

{
  "aria": {
    "label": "My Translatable A11Y Label"
  }
}

To resolve this, it must loop through each layer of nesting to find the appropriate key. Transloco has a tool available which will flatten the file to:

{
  "aria.label": "My Translatable A11Y Label"
}

Allowing for an O(1) (Big O Notation) lookup. Here's a link to the docs on how to achieve it: https://ngneat.github.io/transloco/docs/tools/optimize

Monorepo Support

Transloco also has a tool to extract translations from libraries within a monorepo, or from npm packages, to allow for more control over where we place our translations, allowing them to be close to the files they are used in. Here is a link to the documentation surrounding the Scoped Library Extractor Tool

This Dot is a consultancy dedicated to guiding companies through their modernization and digital transformation journeys. Specializing in replatforming, modernizing, and launching new initiatives, we stand out by taking true ownership of your engineering projects.

We love helping teams with projects that have missed their deadlines or helping keep your strategic digital initiatives on course. Check out our case studies and our clients that trust us with their engineering.

You might also like

Using HttpClient in Modern Angular Applications cover image

Using HttpClient in Modern Angular Applications

Introduction With all the wonderful treats that the Angular team has given us during the recent "renaissance" era, many new developers are joining in on the fun. And one of the challenges they'll face at some point is how to call an API from your Angular application properly. Unfortunately, while searching for a guide on how to do this, they might stumble upon a lot of outdated information. Hence, this article should serve as a reliable guide on how to use the HttpClient in Angular >= 17. The Setup To make an HTTP request in Angular, you can take advantage of the HttpClient provided by the @angular/common/http package. To use it, you'll need to provide it. Here's how you can do that for the whole application using the bootstrapApplication function from @angular/platform-browser: ` With that, you should be good to go. You can now inject the HttpClient into any service or component in your application. Using HttpClient in Services Let's take a common example: You have a database object, say a Movie, and you want to implement CRUD operations on it. Typically, you'll want to create a service that provides methods for these operations. Let's call this service MovieService and create a skeleton for it with a method for getting all movies. ` Implementing the Method using HttpClient Let's assume we have a GraphQL API for our movies. We can implement our getAllMovies using HttpClient to make a request to fetch all movies. First, we will need to define a new type to represent the response from the API. This is especially important when you are using GraphQL, which may return a specific structure, such as: ` When working with a real API, you'll likely use some code generator to generate the types for the response from the GraphQL schema. But for the sake of this example, we'll create an interface to represent the response manually: ` Now, we can implement the getAllMovies method using HttpClient: ` > Note: The post method is used here because we are sending a request body. If you are making a GET request (e.g. to a REST API), you can use the get method instead. The getAllMovies method returns an Observable of MoviesListResponse. In this example, I have typed it explicitly to make it obvious at first glance, but you could also omit the type annotation, and TypeScript should infer it. > Note: While I'm excited about signals as much as the next guy, making HTTP requests is one of the typical async operations for which RxJS Observables are a perfect fit, making a great argument for RxJS still having a solid place in Angular alongside signals. Using the Service in a Component Now that we have our MovieService set up, we can use it as a component to fetch and display all movies. But first, let's create a Movie interface to represent the structure of a movie. Trust me, this will prevent many potential headaches down the line. Although using any at the beginning and implementing the types later is a valid approach in some cases, using data fetched from an API without validating the type will inevitably lead to bugs that are difficult to solve. ` Now, we can start implementing our standalone MoviesComponent: ` In this component, we are calling the getAllMovies method from the MovieService in the constructor to fetch all movies and assign them to the movies property which we will use to display the movies in the template. ` In this case, placing our code inside the constructor is safe because it doesn’t depend on any @Input(). If it were, our code would fail because the inputs aren’t initialized at time of instantiation. That's why it is sometimes recommended to place logic in ngOnInit instead. You could also put this call in an arbitrary method that is called e.g. on a button click. Another way to handle the subscription is to use the async pipe in the template. This way, Angular will automatically subscribe and unsubscribe from the observable for you and you won't have to assign the response to a property in the component. Due to the structure of the returned data, however, we'll need to use the RxJS map operator to extract the movies from the response. ` > Note using the pipe method to chain the map operator to the observable returned by getAllMovies. This is a common pattern when working with RxJS observables introduced in RxJs 5.5. If you see code that uses the map operator directly on the observable and wonder why it isn't working for you, it's likely using an older version of RxJS. Now, we can simply apply the async pipe in the template to subscribe to the observable and display the movies: ` Conclusion HttpClient in Angular is pretty straightforward, but with all the changes to RxJS and Angular in the past few years, it can pose a significant challenge if you're not super-experienced with those technologies and stumble upon outdated resources. Following this article, you should hopefully be able to implement your service using HttpClient to make requests to an API in your modern Angular application and avoid the struggle of copying outdated code snippets....

Incremental Hydration in Angular cover image

Incremental Hydration in Angular

Incremental Hydration in Angular Some time ago, I wrote a post about SSR finally becoming a first-class citizen in Angular. It turns out that the Angular team really treats SSR as a priority, and they have been working tirelessly to make SSR even better. As the previous blog post mentioned, full-page hydration was launched in Angular 16 and made stable in Angular 17, providing a great way to improve your Core Web Vitals. Another feature aimed to help you improve your INP and other Core Web Vitals was introduced in Angular 17: deferrable views. Using the @defer blocks allows you to reduce the initial bundle size and defer the loading of heavy components based on certain triggers, such as the section entering the viewport. Then, in September 2024, the smart folks at Angular figured out that they could build upon those two features, allowing you to mark parts of your application to be server-rendered dehydrated and then hydrate them incrementally when needed - hence incremental hydration. I’m sure you know what hydration is. In short, the server sends fully formed HTML to the client, ensuring that the user sees meaningful content as quickly as possible and once JavaScript is loaded on the client side, the framework will reconcile the rendered DOM with component logic, event handlers, and state - effectively hydrating the server-rendered content. But what exactly does "dehydrated" mean, you might ask? Here's what will happen when you mark a part of your application to be incrementally hydrated: 1. Server-Side Rendering (SSR): The content marked for incremental hydration is rendered on the server. 2. Skipped During Client-Side Bootstrapping: The dehydrated content is not initially hydrated or bootstrapped on the client, reducing initial load time. 3. Dehydrated State: The code for the dehydrated components is excluded from the initial client-side bundle, optimizing performance. 4. Hydration Triggers: The application listens for specified hydration conditions (e.g., on interaction, on viewport), defined with a hydrate trigger in the @defer block. 5. On-Demand Hydration: Once the hydration conditions are met, Angular downloads the necessary code and hydrates the components, allowing them to become interactive without layout shifts. How to Use Incremental Hydration Thanks to Mark Thompson, who recently hosted a feature showcase on incremental hydration, we can show some code. The first step is to enable incremental hydration in your Angular application's appConfig using the provideClientHydration provider function: ` Then, you can mark the components you want to be incrementally hydrated using the @defer block with a hydrate trigger: ` And that's it! You now have a component that will be server-rendered dehydrated and hydrated incrementally when it becomes visible to the user. But what if you want to hydrate the component on interaction or some other trigger? Or maybe you don't want to hydrate the component at all? The same triggers already supported in @defer blocks are available for hydration: - idle: Hydrate once the browser reaches an idle state. - viewport: Hydrate once the component enters the viewport. - interaction: Hydrate once the user interacts with the component through click or keydown triggers. - hover: Hydrate once the user hovers over the component. - immediate: Hydrate immediately when the component is rendered. - timer: Hydrate after a specified time delay. - when: Hydrate when a provided conditional expression is met. And on top of that, there's a new trigger available for hydration: - never: When used, the component will remain static and not hydrated. The never trigger is handy when you want to exclude a component from hydration altogether, making it a completely static part of the page. Personally, I'm very excited about this feature and can't wait to try it out. How about you?...

NgRx Facade Pattern cover image

NgRx Facade Pattern

NgRx Facade Pattern The NgRx Facade Pattern was first introduced by Thomas Burleson in 2018 and has drawn a lot of attention in recent years. In this article, we will discuss the pattern, how to implement it in Angular and discuss whether or not we _should_ implement it. What is NgRx? First, what is NgRx? NgRx is a state management solution for Angular built on top of RxJS which adheres to the redux pattern. It contains an immutable centralized store where the state of our application gets stored. - We select slices of state from the Store using Selectors, which we can then render in our components. - We dispatch Actions to our Store. - Our Store redirects our Action to our Reducers to recalculate our state and replaces the state within our Store. See the diagram below for an illustrated example: This provides us with a tried and tested pattern for managing the state of our application. What is the Facade Pattern? Now that we know what NgRx is, what is the Facade Pattern? Well, what _are_ Facades? Facades are a pattern that provides a simple public interface to mask more complex usage. As we use NgRx more and more in our application, we add more actions and more selectors that our components must use and track. This increases the coupling between our component and the actions and selectors themselves. The Facade pattern wants to simplify this approach by wrapping the NgRx interactions in one place, allowing the Component to only ever interact with the Facade. This means you are free to refactor the NgRx artefacts without worrying about breaking your Components. In Angular, NgRx Facades are simply services. They inject the NgRx Store allowing you to contain your interactions with the Store in the service. How do we implement it? To begin with, let's show a Component that uses NgRx directly: ` As we can see, this depends a lot on interactions with the Store and has made our component fairly complex and coupled to NgRx. Let's create a Facade that will encapsulate this interaction with NgRx: ` It's essentially everything we had in the component, except now in a service. We then inject this service into our Component: ` By implementing the Facade and using it in our Component, our component no longer depends on NgRx and we do not have to import all actions and selectors. The Facade hides those implementation details, keeping our Component cleaner and easier tested. Pros What are some advantages of using Facades? - It adds a single abstraction of a section of the Store. - This service can be used by any component that needs to interact with this section of the store. For example, if another component needs to access the TodoListState from our example above, they do not have to reimplement the action dispatch or state selector code. It's all readily available in the Facade. - Facades are scalable - As Facades are just services, we can compose them within other Facades allowing us to maintain the encapsulation and hide complex logic that interacts directly with NgRx, leaving us with an API that our developers can consume. Cons - Facades lead to reusing Actions. - Mike Ryan gave a talk at ng-conf 2018 on Good Action Hygiene which promotes creating as many actions as possible that dictate how your user is using your app and allowing NgRx to update the state of the application from your user's interactions. - Facades force actions to be reused. This becomes a problem as we no longer update state based on the user's interactions. Instead, we create a coupling between our actions and various component areas within our application. - Therefore, by changing one action and one accompanying reducer, we could be impacting a significant portion of our application. - We lose indirection - Indirection is when a portion of our app is responsible for certain logic, and the other pieces of our app (the view layer etc.) communicate with it via messages. - In NgRx, this means that our Effects or Reducers do not know what told them to work; they just know they have to. - With Facades, we hide this indirection as only the service knows about how the state is being updated. - Knowledge Cost - It becomes more difficult for junior developers to understand how to interact, update and work with NgRx if their only interactions with the state management solution are through Facades. - It also becomes more difficult for them to write new Actions, Reducers and Selectors as they may not have been exposed to them before. Conclusion Hopefully, this gives you an introduction to NgRx Facades and the pros and cons of using them. This should help you evaluate whether to use them or not....

This Dot AI Field Notes - Anatomy of a Coding Harness cover image

This Dot AI Field Notes - Anatomy of a Coding Harness

A coding agent is not magic, it’s a loop. We call this a harness. The harness is a deterministic layer of code that wraps an LLM. Claude Code is a harness. Codex is a harness. Pi is a harness. The harness, on initialization, provides to the LLM a system prompt defining all tools the harness implements for the LLM. Without the harness, you cannot read or modify files on the user’s local filesystem without them having to copy-and-pasting by hand. The harness is the final place where engineers can customize how coding agents do work before the LLM takes over. Think of the LLM as a train and the harness as the rails the train rides on. Below… one full task executed by a harness, traced step by step....

Let's innovate together!

We're ready to be your trusted technical partners in your digital innovation journey.

Whether it's modernization or custom software solutions, our team of experts can guide you through best practices and how to build scalable, performant software that lasts.

Prefer email? hi@thisdot.co