Create Angular 9/8 MultiLingual Site with ngx-translate i18n Library

Last updated on by Digamber
In this Angular 9/8 Internationalization (i18n) tutorial, we will look at how to create a MultiLingual Angular 9 site using ngx-translate library.

Angular 9 Internationalization (i18n)

NGX-Translate is an internationalization library for Angular. It allows you to Internationalize the Angular app in multiple languages.

You can easily convert static or dynamic data into various languages. It provides you useful service, a directive, and a pipe to manipulate any data.

What is Internationalization?

Internationalization is the process of designing and preparing your app to be usable in different languages. Localization is the process of translating your internationalized app into specific languages for particular locales.
angular.io

Building a user-friendly application is every product owner’s goal; various factors enhance the user experience of an app. To entertain a user, an application must be usable, findable, credible, desirable, and valuable, but most importantly, it should be accessible to worldwide users.

Every text on the application should be localized so that anyone can access the information provided on the app. In this tutorial, we will learn how to create an Angular app, which supports multiple languages. Various methods help in translating an Angular app, such as using the built-in i18n tool or by using the ngx-translate plugin.

We are going to internationalize our basic Angular 9 app using a third party plugin called ngx-translate.

Let’s start coding our app.

Prerequisites

  • Angular CLI
  • Understanding of Angular
  • Latest version of Node and NPM
  • IDE or Code editor

If you are new to Angular then check out this basic tutorial, in this tutorial we can learn how to create a basic CRUD app with Angular.

Create Angular 9 Demo App

I believe that you already have Angular CLI installed on your machine. If not, then run the following command.

npm install -g @angular/cli

Run the following command to create a brand new Angular 9 project.

ng new angular-translate-app

# Would you like to add Angular routing? No
# Which stylesheet format would you like to use? CSS

Head over to the project.

cd angular-translate-app

For the demo purpose, we will be creating a Basic form. So, install the Bootstrap package to create the form quickly.

npm install bootstrap

Add the Bootstrap CSS path in styles array inside the angular.json file.

"styles": [
    "src/styles.css",
    "node_modules/bootstrap/dist/css/bootstrap.min.css"
]

Start the app in the browser.

ng serve --open

Adding ngx-translate in Angular 9 App

Run the following command to install the ngx-translate packages in Angular application.

npm i @ngx-translate/core --save
npm i @ngx-translate/http-loader --save

The @ngx-translate/core package includes the essential services, pipe, and directives, to convert the content in various languages.

The @ngx-translate/http-loader service helps in fetching the translation files from a webserver.

Next, import and register the TranslateModule in app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

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

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

export class AppModule { }

// AOT compilation support
export function httpTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

You can easily create your own loader, and It can be done by implementing the TranslateLoader interface and provide it in AppModule as given above. The httpTranslateLoader function is needed during the build phase (AOT) in our project.

Configure Translation Files

Open the assets folder and create “i18n” folder inside of it. In “i18n” folder, you have to add lang.json files along with the country code.

You can add as many languages as you want in i18n folder. A translation file is just another JSON file, In this file we have to define the language’s data in key-value pairs format.

In this tutorial we will focus on English and Dutch languages.

To configure the translation loader, we need to create the lang.json file based on the languages we want to translate. Add the language code instead of lang, for instance, if your language is English, this will become en.json.

Check out here to know more about the i18n country codes.

Add the English (en) values in key-value pair format in src/assets/en.json file.

{
    "Sitetitle": "Angular Multi Language Site",
    "Name": "Name",
    "NameError": "I am sure you must have a name!",
    "Email": "Email address",
    "PhoneNo": "Phone No",
    "Password": "Password",
    "Bio": "Enter bio",
    "TermsConditions": "I agree to terms and conditions.",
    "Submit": "Submit"
}

Add the Dutch (nl) values in key-value pair format in src/assets/nl.json file.

{
    "Sitetitle": "Hoekige site met meerdere talen",
    "Name": "Naam",
    "NameError": "Ik weet zeker dat je een naam moet hebben",
    "Email": "E-mailadres",
    "PhoneNo": "Telefoon nr",
    "Password": "Wachtwoord",
    "Bio": "Voer bio in",
    "TermsConditions": "Ik ga akkoord met de voorwaarden.",
    "Submit": "voorleggen"
}

Implementing Translations with TranslateService

In this step, we will learn how to implement translations, Import TranslateService in app.component.ts file.

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

Next, inject TranslateService in the constructor. It allows us to access the translation service’s methods.

export class AppComponent {
  constructor(
    public translate: TranslateService
  ) {
    translate.addLangs(['en', 'nl']);
    translate.setDefaultLang('en');
  }
}

Let’s understand what we did above, by setting up the translate.addLangs([‘en’, ‘nl’]) method, we informed the service that what languages need to be translated.

We defined the translate.setDefaultLang(‘en’) method and passed the English language as a fallback translation, especially for the missing translations scenario for existing language.

The language parameter you see here are the same parameters that we defined with the JSON file. These parameters are the building bridge to make your site multi-language supportable.

Adding Language Switcher

To change the language of our Angular site, we will implement a simple dropdown and create a switchLang() function.

This function takes a single language parameter, and on changing the value of the dropdown, we will call this.translate.use(lang) method to change the language of the site.

We will bind switchLang() to a select dropdown; this simple select dropdown will have the language list and translate the site content based on the user’s language preference.

switchLang(lang: string) {
  this.translate.use(lang);
}

Add the following code in the app.component.html template.

<span class="form-inline">
  <select 
      class="form-control" 
      #selectedLang 
      (change)="switchLang(selectedLang.value)">
    <option *ngFor="let language of translate.getLangs()" 
      [value]="language"
      [selected]="language === translate.currentLang">
      {{ language }}
    </option>
  </select>
</span>

Configure Translations with TranslatePipe

We created a basic Bootstrap user form to give you Angular 8/9 Internationalization (i18n) demo.

We have a user object defined in the en.json and nl.json file. With the help of a translate pipe, we are going to translate our Angular 8/9 app.

In the {{‘Sitetitle’ | translate }} double curly braces, we pass the first value as the same value as we defined in the lang.json file. Second value is the TranslatePipe | translate to internationalize with ngx-translate.

Add the following code inside the app.component.html file.

<nav class="navbar navbar-dark bg-primary">
  <div class="container">
    <a class="navbar-brand">
      {{'Sitetitle' | translate }}
    </a>
    <span class="form-inline">
      <select class="form-control" #selectedLang (change)="switchLang(selectedLang.value)">
        <option *ngFor="let language of translate.getLangs()" [value]="language"
          [selected]="language === translate.currentLang">
          {{ language }}
        </option>
      </select>
    </span>
  </div>
</nav>

<div class="container">
  <form>
    <div class="form-group">
      <label>{{'Name' | translate}}</label>
      <input type="text" class="form-control">
      <small class="text-danger">{{'NameError' | translate}}</small>
    </div>

    <div class="form-group">
      <label>{{'Email' | translate}}</label>
      <input type="email" class="form-control">
    </div>

    <div class="form-group">
      <label>{{'PhoneNo' | translate}}</label>
      <input type="tel" class="form-control">
    </div>

    <div class="form-group">
      <label>{{'Password' | translate}}</label>
      <input type="password" class="form-control">
    </div>

    <div class="form-group">
      <label>{{'Bio' | translate}}</label>
      <textarea rows="3" class="form-control"></textarea>
    </div>

    <div class="form-group form-check">
      <input type="checkbox" class="form-check-input">
      <label class="form-check-label">{{'TermsConditions' | translate}}</label>
    </div>
    <button type="submit" class="btn btn-block btn-danger">{{'Submit' | translate}}</button>
  </form>
</div>

Conclusion

Finally, we have completed the Angular 9/8 Internationalization (i18n) tutorial, and In this tutorial, we learned how to build a multilingual Angular app using ngx-translate plugin easily.

We looked at how to set up an environment for translating an Angular app, how to access translate service’s methods, and using TranslatePipe. I hope you liked this tutorial; please share it with others.

You can download the complete code of this tutorial on this GitHub repository.

Digamber
Digamber

Digamber Rawat is from Dev Bhoomi Uttarakhand, located in northwestern part of India. He is a Data Scientist by profession and a primary author of this blog.