Contents hide 1) Angular 12 with ngx-translate 2) Add ngx-translate to angular app 3) Setup translations JSON file 4) Create Internationalization Module 4.1) Internationalization Module 4.2) Localization Configuration Service 4.3) Localization Service 5) Using Internationalization Module 5.1) Using translate method 5.2) Using translate pipe Code and Demo This tutorial will see how we can Easily Translate the Angular 12 App Using the library Angular 12 with ngx-translate The internationalization (i18n) library for Angular ngx-translate: It is an internationalization library for Angular. It will let you define translations for your content in different languages and you can switch languages easily. The ngx-translate library provides you a service, a directive, and a pipe to handle any dynamic or static content. NGX-Translate is also extremely modular. It is written in a way that makes it really easy to replace any part with a custom implementation in case the existing one doesnβt fit your needs. Add ngx-translate to angular app Letβs first import the ngx-translate library using the NPM command, Here we going to import 2 packages of ngx-translate @ngx-translate/core: ^13.0.0 β contains core methods @ngx-translate/http-loader: ^6.0.0 β contains methods to load translation files. bash npm i @ngx-translate/core --save npm i @ngx-translate/http-loader --save Setup translations JSON file ngx-translate uses the JSON file to fetch the translation keys and words from it. the file must be in JSON format and each language should have different files. Each language file can be uniquely named as per the application requirements. letβs assume we are giving 3 language support to an application, so we can add that JSON file in a separate folder inside the assets directory. The reason we are storing it in the assets directory is those are external files and they must be saved in a bundle while the build is done by angular CLI. Directory |-- src | |-- app | |-- assets | |-- locales | |-- en-US.json | |-- fr-FR.json | |-- hi-IN.json en-US.json { "banner": { "hello" : "Hello", "world": "world", "change_lang_label": "Change The Language From Below Drop Down" } } So in each file, you can add a translated text. in this file, you can create nested objects and arrays and can be iterate on HTML. Create Internationalization Module Will create a separate Internationalization module to handle all the functionality of language change and default language initialization. Directory |-- src | |-- app | |-- internationalization // CLI: ng g m internationalization | |-- internationalization.module.ts // created by above CLI command | |-- localization-config.service.ts // CLI: ng g service localization-config | |-- localization.service.ts // CLI: ng g service localization Internationalization Module Make the internationalization module configurable with forRoot so when the app is initiated we can have a default language loaded in the module. internationalization.module.ts import { APP_INITIALIZER, LOCALE_ID, ModuleWithProviders, NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LocalizationService } from './localization.service'; import { LocalizationServiceConfig } from './localization-config.service'; import { TranslateModule } from '@ngx-translate/core'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [], imports: [CommonModule, HttpClientModule, TranslateModule.forChild()], exports: [TranslateModule] }) export class InternationalizationModule { public static forRoot(config: any): ModuleWithProviders<InternationalizationModule> { return { ngModule: InternationalizationModule, providers: [ { provide: APP_INITIALIZER, useFactory: initLocalizationService, deps: [LocalizationService], multi: true }, LocalizationService, { provide: LOCALE_ID, useValue: config.locale_id }, // using the initial value { provide: LocalizationServiceConfig, useValue: config } ] }; } } /** * Initialize the localization service. * @param {LocalizationService} service * @returns {() => Promise<void>} */ export function initLocalizationService(service: LocalizationService) { return () => service.initService(); } Localization Configuration Service The configuration is just to set the options we will be using inside the module. For example, our default language will be English (en-US). localization-config.service.ts import { Injectable } from '@angular/core'; /** * Class representing the localization config */ @Injectable() export class LocalizationServiceConfig { public locale_id: string = ''; } Localization Service Localization Service will have all the methods for changing language, initializing the default language, and a method that we can use in the TS file for translation. localization.service.ts import { Injectable, Optional, SkipSelf } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { LocalizationServiceConfig } from './localization-config.service'; /** * Class representing the translation service. */ @Injectable() export class LocalizationService { private _localeId: string = 'en-US'; // default /** * @constructor * @param {LocalizationService} singleton - the localization service * @param {LocalizationServiceConfig} config - the localization config * @param {TranslateService} translateService - the translate service */ constructor( @Optional() @SkipSelf() private singleton: LocalizationService, private config: LocalizationServiceConfig, private translateService: TranslateService ) { if (this.singleton) { throw new Error( 'LocalizationService is already provided by the root module' ); } this._localeId = this.config.locale_id; } /** * Initialize the service. * @returns {Promise<void>} */ public initService(): Promise<void> { // language code same as file name. this._localeId = localStorage.getItem('language') || 'en-US'; return this.useLanguage(this._localeId); } /** * change the selected language * @returns {Promise<void>} */ public useLanguage(lang: string): Promise<void> { this.translateService.setDefaultLang(lang); return this.translateService .use(lang) .toPromise() .catch(() => { throw new Error('LocalizationService.init failed'); }); } /** * Gets the instant translated value of a key (or an array of keys). * @param key * @param interpolateParams * @returns {string|any} */ public translate(key: string | string[], interpolateParams?: object): string { return this.translateService.instant(key, interpolateParams) as string; } } Note: β We have to use the local storage to maintain the user session. As if the user returns to the app so we can default load the last selected language. β filename and language code must be same. Using Internationalization Module Till now we have created a configurable module for localization using ngx-translate library methods. Now will use that module on the root level of the app. app.module.ts ... import { InternationalizationModule } from './internationalization/internationalization.module'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; /** * The http loader factory : Loads the files from define path. * @param {HttpClient} http * @returns {TranslateHttpLoader} * @constructor */ export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http, '../assets/locales/', '.json'); } @NgModule({ imports: [ ..., HttpClientModule, InternationalizationModule.forRoot({ locale_id: 'en-US' }), // iniating with default language: en-US TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }) ], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {} Using translate method We can use the translate in any *.component.ts file by using a method that we created in localization.service.ts app.component.ts ... export class AppComponent { ... constructor(private localizationService: LocalizationService) {} ... get name(): string { return this.localizationService.translate('banner.world'); } ... } Using translate pipe We can also you the translate pipe. so whatever language is set it will translate the content in that language. app.component.html <h1>{{ 'banner.hello' | translate }} {{ name }}!</h1> SEE THE WORKING DEMO ON : https://stackblitz.com Get More tutorials on Angular 12 Share this:TwitterFacebookRedditLinkedInWhatsAppPrintTumblr Related Tags: @ngx-translate/core, Angular 12, i18n, Internationalization