Receive notifications about upcoming Intlayer releases
    Creation:2025-04-18Last update:2025-06-29

    Getting Started with Internationalization (i18n) in Angular using Intlayer

    This package is in development. See the issue for more information. Show your interest in Intlayer for Angular by liking the issue

    What is Intlayer?

    Intlayer is an innovative, open-source internationalization (i18n) library designed to simplify multilingual support in modern web applications.

    With Intlayer, you can:

    • Easily manage translations using declarative dictionaries at the component level.
    • Dynamically localize metadata, routes, and content.
    • Ensure TypeScript support with autogenerated types, improving autocompletion and error detection.
    • Benefit from advanced features, like dynamic locale detection and switching.

    Step-by-Step Guide to Set Up Intlayer in an Angular Application

    Step 1: Install Dependencies

    Install the necessary packages using npm:

    bash
    npm install intlayer angular-intlayer @intlayer/webpack
    • intlayer

      The core package that provides internationalization tools for configuration management, translation, content declaration, transpilation, and CLI commands.

    • angular-intlayer The package that integrates Intlayer with Angular application. It provides context providers and hooks for Angular internationalization.

    • @intlayer/webpack

      The package that integrates Intlayer with Webpack. It is used by the Angular CLI to build content declaration files and monitor them in development mode.

    Step 2: Configuration of your project

    Create a config file to configure the languages of your application:

    intlayer.config.ts
    import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = {  internationalization: {    locales: [      Locales.ENGLISH,      Locales.FRENCH,      Locales.SPANISH,      // Your other locales    ],    defaultLocale: Locales.ENGLISH,  },};export default config;

    Through this configuration file, you can set up localized URLs, middleware redirection, cookie names, the location and extension of your content declarations, disable Intlayer logs in the console, and more. For a complete list of available parameters, refer to the configuration documentation.

    Step 3: Integrate Intlayer in Your Angular Configuration

    To integrate Intlayer with the Angular CLI, you have two options depending on your builder: esbuild or webpack.

    First, modify your angular.json to use the custom esbuild builder. Update the build configuration:

    angular.json
    {  "projects": {    "your-app-name": {      "architect": {        "build": {          "builder": "@angular-builders/custom-esbuild:application",          "options": {            "plugins": ["./esbuild/intlayer-plugin.ts"]          }        }      }    }  }}

    Make sure to replace your-app-name with the actual name of your project in angular.json.

    Next, create an esbuild/intlayer-plugin.ts file in your project's root:

    esbuild/intlayer-plugin.ts
    import { prepareIntlayer, watch } from "@intlayer/chokidar";import { getConfiguration, logger } from "@intlayer/config";import type { Plugin } from "esbuild";const intlayerPlugin: Plugin = {  name: "intlayer-esbuild-plugin",  setup(build) {    const configuration = getConfiguration();    let isWatching = false;    build.onStart(async () => {      logger("Intlayer esbuild plugin started", {        level: "info",      });      if (build.initialOptions.watch && !isWatching) {        logger("Watch mode enabled. Starting watcher...", {          level: "info",        });        watch(configuration);        isWatching = true;      }      try {        await prepareIntlayer(configuration);      } catch (error) {        logger(`Error in Intlayer esbuild plugin: ${error}`, {          level: "error",        });      }    });  },};export default intlayerPlugin;

    The intlayerPlugin for esbuild ensures that Intlayer is prepared before the build starts and watches for changes in development mode.

    Option 2: Using Webpack

    First, modify your angular.json to use the custom Webpack builder. Update the build and serve configurations:

    angular.json
    {  "projects": {    "your-app-name": {      "architect": {        "build": {          "builder": "@angular-builders/custom-webpack:browser",          "options": {            "customWebpackConfig": {              "path": "./webpack.config.js"            }          }        },        "serve": {          "builder": "@angular-builders/custom-webpack:dev-server"        }      }    }  }}

    Make sure to replace your-app-name with the actual name of your project in angular.json.

    Next, create a webpack.config.js file at the root of your project:

    webpack.config.js
    const { IntlayerWebpackPlugin } = require("@intlayer/webpack");module.exports = {  plugins: [new IntlayerWebpackPlugin()],};

    The IntlayerWebpackPlugin is used to integrate Intlayer with Webpack. It ensures the building of content declaration files and monitors them in development mode. It defines Intlayer environment variables within the application. Additionally, it provides aliases to optimize performance.

    Step 4: Declare Your Content

    Create and manage your content declarations to store translations:

    src/app/app.content.ts
    import { t, type Dictionary } from "intlayer";const appContent = {  key: "app",  content: {    title: t({      en: "Hello",      fr: "Bonjour",      es: "Hola",    }),    congratulations: t({      en: "Congratulations! Your app is running. 🎉",      fr: "Félicitations! Votre application est en cours d'exécution. 🎉",      es: "¡Felicidades! Tu aplicación está en ejecución. 🎉",    }),    exploreDocs: t({      en: "Explore the Docs",      fr: "Explorer les Docs",      es: "Explorar los Docs",    }),    learnWithTutorials: t({      en: "Learn with Tutorials",      fr: "Apprendre avec les Tutoriels",      es: "Aprender con los Tutorios",    }),    cliDocs: "CLI Docs",    angularLanguageService: t({      en: "Angular Language Service",      fr: "Service de Langage Angular",      es: "Servicio de Lenguaje Angular",    }),    angularDevTools: "Angular DevTools",    github: "Github",    twitter: "Twitter",    youtube: "Youtube",  },} satisfies Dictionary;export default appContent;

    Your content declarations can be defined anywhere in your application as soon they are included into the contentDir directory (by default, ./src). And match the content declaration file extension (by default, .content.{json,ts,tsx,js,jsx,mjs,mjx,cjs,cjx}).

    For more details, refer to the content declaration documentation.

    Step 5: Utilize Intlayer in Your Code

    To utilize Intlayer's internationalization features throughout your Angular application, you need to use the useIntlayer function within a component. This function, available from angular-intlayer, provides access to your translations as reactive signals.

    IntlayerProvider is registered in the root of the application, so you don't need to add it to your module's providers.

    Access your content dictionaries in your component class:

    src/app/hello-world.component.ts
    import { Component, signal } from "@angular/core";import { useIntlayer } from "angular-intlayer";@Component({  selector: "app-hello-world",  standalone: true,  template: `    <h1>{{ content().title }}</h1>    <div class="card">      <button type="button" (click)="increment()">        {{ content().count }} {{ count() }}      </button>      <p [innerHTML]="content().edit"></p>    </div>    <p class="read-the-docs">{{ content().readTheDocs }}</p>  `,})export class HelloWorldComponent {  content = useIntlayer("helloworld");  count = signal(0);  increment() {    this.count.update((value) => value + 1);  }}

    Intlayer content is returned as a Signal, so you access the values by calling the signal in your template: content().title.

    (Optional) Step 6: Change the language of your content

    To change the language of your content, you can use the setLocale function provided by the useLocale function. This allows you to set the locale of the application and update the content accordingly.

    Create a component to switch between languages:

    src/app/components/locale-switcher.component.ts
    import { Component } from "@angular/core";import { CommonModule } from "@angular/common";import { getLocaleName } from "intlayer";import { useLocale } from "angular-intlayer";import { FormsModule } from "@angular/forms";@Component({  selector: "app-locale-switcher",  standalone: true,  imports: [CommonModule, FormsModule],  template: `    <div class="locale-switcher">      <select [ngModel]="locale()" (ngModelChange)="changeLocale($event)">        <option *ngFor="let loc of availableLocales" [value]="loc">          {{ getLocaleName(loc) }}        </option>      </select>    </div>  `,})export class LocaleSwitcherComponent {  localeInfo = useLocale();  locale = this.localeInfo.locale;  availableLocales = this.localeInfo.availableLocales;  // Expose getLocaleName to the template  getLocaleName = getLocaleName;  changeLocale(newLocale: string) {    this.localeInfo.setLocale(newLocale);  }}

    Then, use this component in your app.component.ts:

    src/app/app.component.ts
    import { Component } from "@angular/core";import { HelloWorldComponent } from "./hello-world.component";import { LocaleSwitcherComponent } from "./components/locale-switcher.component";@Component({  selector: "app-root",  standalone: true,  imports: [HelloWorldComponent, LocaleSwitcherComponent],  template: `    <div>      <app-locale-switcher />      <a href="https://vite.dev" target="_blank">        <img src="/vite.svg" class="logo" alt="Vite logo" />      </a>      <a href="https://angular.dev/" target="_blank">        <img          src="/assets/angular.svg"          class="logo angular"          alt="Angular logo"        />      </a>    </div>    <app-hello-world />  `,})export class AppComponent {}

    (Optional) Step 7: Add localized Routing to your application

    Adding localized routing in an Angular application involves using the Angular Router with locale prefixes. This creates unique routes for each language, which is useful for SEO.

    Example:

    plaintext
    - https://example.com/about- https://example.com/es/about- https://example.com/fr/about

    First, ensure you have @angular/router installed.

    Then, create a router configuration that handles locale-based routing in app.routes.ts.

    src/app/app.routes.ts
    import { Routes } from "@angular/router";import { configuration, localeFlatMap } from "intlayer";import { HomeComponent } from "./home/home.component";import { RootComponent } from "./root/root.component";const { defaultLocale } = configuration.internationalization;export const routes: Routes = [  localeFlatMap((localizedData) => [    {      path: `${localizedData.urlPrefix}`,      component: RootComponent,      data: { locale: localizedData.locale },    },    {      path: `${localizedData.urlPrefix}/home`,      component: HomeComponent,      data: { locale: localizedData.locale },    },  ]),  { path: "**", redirectTo: `/${defaultLocale}/home` },];

    Then, you need to provide the router in your app.config.ts.

    src/app/app.config.ts
    import { ApplicationConfig } from "@angular/core";import { provideRouter } from "@angular/router";import { routes } from "./app.routes";export const appConfig: ApplicationConfig = {  providers: [provideRouter(routes)],};

    (Optional) Step 8: Change the URL when the locale changes

    To automatically update the URL when the user changes the language, you can modify the LocaleSwitcher component to use Angular's Router:

    src/app/components/locale-switcher.component.ts
    import { Component, inject } from "@angular/core";import { CommonModule } from "@angular/common";import { Router } from "@angular/router";import { getLocaleName, getLocalizedUrl } from "intlayer";import { useLocale } from "angular-intlayer";import { FormsModule } from "@angular/forms";@Component({  selector: "app-locale-switcher",  standalone: true,  imports: [CommonModule, FormsModule],  template: `    <div class="locale-switcher">      <select [ngModel]="locale()" (ngModelChange)="changeLocale($event)">        <option *ngFor="let loc of availableLocales" [value]="loc">          {{ getLocaleName(loc) }}        </option>      </select>    </div>  `,})export class LocaleSwitcherComponent {  private router = inject(Router);  localeInfo = useLocale({    onLocaleChange: (newLocale) => {      const currentPath = this.router.url;      const localizedPath = getLocalizedUrl(currentPath, newLocale);      this.router.navigateByUrl(localizedPath);    },  });  locale = this.localeInfo.locale;  availableLocales = this.localeInfo.availableLocales;  getLocaleName = getLocaleName;  changeLocale(newLocale: string) {    this.localeInfo.setLocale(newLocale);  }}

    (Optional) Step 9: Switch the HTML Language and Direction Attributes

    When your application supports multiple languages, it's crucial to update the <html> tag's lang and dir attributes to match the current locale.

    You can create a service to handle this automatically.

    src/app/services/i18n-html-attributes.service.ts
    import { Injectable, effect } from "@angular/core";import { useLocale } from "angular-intlayer";import { getHTMLTextDir } from "intlayer";@Injectable({  providedIn: "root",})export class I18nHtmlAttributesService {  private localeInfo = useLocale();  constructor() {    effect(() => {      const newLocale = this.localeInfo.locale();      if (newLocale) {        document.documentElement.lang = newLocale;        document.documentElement.dir = getHTMLTextDir(newLocale);      }    });  }  // This method can be called in the app's root component to ensure the service is initialized.  init() {}}

    Then, inject and initialize this service in your main AppComponent:

    src/app/app.component.ts
    import { Component, inject } from "@angular/core";// ... other importsimport { I18nHtmlAttributesService } from "./services/i18n-html-attributes.service";@Component({  // ...})export class AppComponent {  constructor() {    inject(I18nHtmlAttributesService).init();  }}

    To ensure that your application's navigation respects the current locale, you can create a custom directive. This directive automatically prefixes internal URLs with the current language.

    src/app/directives/localized-link.directive.ts
    import { Directive, Input, HostBinding, inject } from "@angular/core";import { getLocalizedUrl } from "intlayer";import { useLocale } from "angular-intlayer";@Directive({  selector: "a[appLocalizedLink]",  standalone: true,})export class LocalizedLinkDirective {  @Input("href") originalHref: string = "";  private localeInfo = useLocale();  @HostBinding("href")  get localizedHref(): string {    const locale = this.localeInfo.locale();    const isExternalLink = /^https?:\/\//.test(this.originalHref);    if (isExternalLink || !this.originalHref) {      return this.originalHref;    }    return getLocalizedUrl(this.originalHref, locale);  }}

    To use it, add the appLocalizedLink directive to your anchor tags and make sure to import it in your component.

    src/app/app.component.ts
    // ...import { LocalizedLinkDirective } from "./directives/localized-link.directive";@Component({  selector: "app-root",  standalone: true,  imports: [/*...,*/ LocalizedLinkDirective],  template: ` <a href="/home" appLocalizedLink>Home</a> `,})export class AppComponent {}

    (Optional) Step 11: Render Markdown

    Intlayer supports rendering Markdown content. To convert Markdown into rich HTML, you can integrate markdown-it.

    First, install markdown-it:

    bash
    npm install markdown-it# and its typesnpm install -D @types/markdown-it

    Next, configure the INTLAYER_MARKDOWN_TOKEN in your app.config.ts.

    src/app/app.config.ts
    import { ApplicationConfig } from "@angular/core";import { provideRouter } from "@angular/router";import { routes } from "./app.routes";import { createIntlayerMarkdownProvider } from "angular-intlayer/markdown";import MarkdownIt from "markdown-it";const md = new MarkdownIt({  html: true,  linkify: true,  typographer: true,});export const appConfig: ApplicationConfig = {  providers: [    provideRouter(routes),    createIntlayerMarkdownProvider((markdown) => md.render(markdown)),  ],};

    By default, Intlayer will return the rendered HTML as a string. If you use [innerHTML] to bind it, be aware of the security implications (XSS). Always ensure your content is from a trusted source.

    For more complex scenarios, you can create a pipe to safely render the HTML.

    Configure TypeScript

    Intlayer uses module augmentation to get benefits of TypeScript and make your codebase stronger.

    alt text

    alt text

    Ensure your TypeScript configuration includes the autogenerated types.

    tsconfig.json
    {  // ... Your existing TypeScript configurations  "include": [    // ... Your existing TypeScript configurations    ".intlayer/**/*.ts", // Include the auto-generated types  ],}

    Git Configuration

    It is recommended to ignore the files generated by Intlayer. This allows you to avoid committing them to your Git repository.

    To do this, you can add the following instructions to your .gitignore file:

    plaintext
    # Ignore the files generated by Intlayer.intlayer

    VS Code Extension

    To improve your development experience with Intlayer, you can install the official Intlayer VS Code Extension.

    Install from the VS Code Marketplace

    This extension provides:

    • Autocompletion for translation keys.
    • Real-time error detection for missing translations.
    • Inline previews of translated content.
    • Quick actions to easily create and update translations.

    For more details on how to use the extension, refer to the Intlayer VS Code Extension documentation.


    Go Further

    To go further, you can implement the visual editor or externalize your content using the CMS.


    Doc History

    Version Date Changes
    5.5.10 2025-06-29 Init history
    Receive notifications about upcoming Intlayer releases