Tuesday, May 26, 2020

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

In this Angular 10/9/8 Internationalization (i18n) tutorial, we will look at how to create a MultiLingual Angular site using ngx-translate library.
Create Angular 10/9/8 MultiLingual Site with ngx-translate i18n Library

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 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 10/9/8 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>

No comments:

Post a Comment