Localization or i18n Using ngx-translate In Angular

Internationalization :

Internationalization allows the programme to handle many languages. This enables the same programme to be translated into a certain language for a specified location.

Why Ngx Translate ?

To perform Internationalization Ngx-trnslate is used.

It’s a third-party pulgin that’ll make the process go as smoothly as possible. A number of production-level applications already utilise the Ngx Translate plugin extensively. The use of translation in static and dynamic data-driven Angular apps is fully supported.

Getting the Project Started :

Add certain dependencies to a completely new Angular application.

First we’ll create new application

ng new angular-ngx-translate-example --skip-tests

After that navigate to the newly created project directory

cd angular-ngx-translate-example

Next, run the following command to add the package to your application:

npm install @ngx-translate/core@13.0.0

Now import the TranslateModule in your AppModule:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    TranslateModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

This will provide you access to the translate service’s core, pipe, and directives.

Unless you plan on manually adding each translation via code, you’ll probably want to add some setup at this point to make importing your translations a little easier.

Using TranslateHttpLoader :

Including your translation files as assets and loading them using the TranslateHttpLoader, which is available in a separate npm package, is probably the most frequent approach to load translations.

npm install @ngx-translate/http-loader@6.0.0

Now import the TranslateHttpLoader in your AppModule:

app.component.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

import { AppComponent } from './app.component';

// AoT requires an exported function for factories
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
          useFactory: HttpLoaderFactory,
          deps: [HttpClient]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Translation File :

This method of creating the translation loader assumes that you have a file named lang.json in your project’s /assets/i18n/ folder, where lang is the language of the file you’re utilizing for translations. This file may be named en.json in English, for example.

A translation file is a JSON object that contains key-value pairs, with the key describing the text to be translated and the value being the translated text in the language indicated by the file.

For Example :

en.json(english) :

{
  "welcomeMessage": "Thanks for joining ! It's great to have you!",
}

es.json(spanish) :

{
  "welcomeMessage": "Gracias por unirte ! es genial tenerte !",
}

Accessing Translations :

app.component.ts

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(translate: TranslateService) {
    translate.addLangs(['en', 'klingon']);
    translate.setDefaultLang('en');
    translate.use('en');
  }
}

Translate first. addLangs([]) informs the service about the languages that can be used for translations.

You can use the method translate.setDefaultLang(‘en’) to define a fallback set of translations to use if the current language’s translations are missing.

translate.use(‘en’) instructs the service to use English as the current translation language.

Using TranslatePipe

Syntax :

{{ “KEY” } | translate }

Example :

<p>
    {{ 'welcomeMessage' | translate }}
</p>

OutPut :

The output will be based on the language set in app.component.ts file

If the language is English then the output content will print from en.json , If Spanish then from es.json

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories