Angular Internationalization (i18n)

New Transloco approach:

Summary:

Migrate from ngx-translate to Transloco script:


ng g @ngneat/transloco:migrate

Links:

Popular ngx-translate approach:

Summary:

Official Angular i18n approach:

Summary:

  • Complex to setup: separate build per every language in production
  • Complex in development: separate local server instance per every language
  • Run command to extract language strings

Run CLI command:


ng add @angular/localize

Add i18n attr:


<h1 i18n="@@introHeader">

  Hello i18n!

</h1>



<ng-container i18n="@@introDesc">I don't output any element</ng-container>

Run this CLI command to extract the source language file:


ng extract-i18n --output-path src/locale

Copy file src/locale/messages.xlf into src/locale/messages.fr.xlf.

Also add "target" for every "source" with French translation inside messages.fr.xlf:


<source>Homepage</source>

<target>Page d'accueil</target>

Angular.json update:


  "projects": {

    "project-name": {

      "i18n": {

        "sourceLocale": "en",

        "locales": {

          "fr": {

            "translation": "src/locale/messages.fr.xlf",

            "baseHref": ""

          }

        }

      },

      "architect": {

        "build": {

          "options": {

            "localize": true,

            "aot": true,

          },

          "configurations": {

            "production": {},

            "en": {

              "localize": ["en"],

              "main": "src/main.ts"

            },

            "fr": {

              "localize": ["fr"],

              "main": "src/main.ts"

            }

          }

        },

        "serve": {

          "builder": "@angular-devkit/build-angular:dev-server",

          "options": {

            "browserTarget": "project-name:build"

          },

          "configurations": {

            "production": {

              "browserTarget": "project-name:build:production"

            },

            "en": {

              "browserTarget": "project-name:build:en"

            },

            "fr": {

              "browserTarget": "project-name:build:fr"

            }

          }

        },

      }

    }

  }

Serve English localized page locally via http://localhost:420/:


ng serve --configuration=en

Serve French localized page locally via http://localhost:4201/:


ng serve --configuration=fr --port 4201

Leave a Comment