6

Diversifying Angular app - multi-lingual support - Knoldus Blogs

 3 years ago
source link: https://blog.knoldus.com/diversifying-angular-app-multi-lingual-support/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Diversifying Angular app – multi-lingual support

Reading Time: 7 minutes

Hi! Welcome abroad on this journey. Today, we are going to create an Angular app that supports multi-languages.

Angular app with multi-language support will be more understandable. How you ask? Let’s explain this with an example – an app with cultural language support will have more wider audience than a normal app which only supports the international language of business (English).

Therefore, it’s important to know how to create an angular app that supports the multi-languages using the ngx-translate NPM package, which just makes things much easier for us (the developers).

What we are going to achieve at the end of this tutorial –

  • Overview of angular internationalization
  • How to use the ngx-translate library for supporting the angular app in two different languages?

Assumptions –

  • You have basic knowledge of angular, if not then please go through these other blogs/tutorials from Knoldus or you can visit the official angular docs.
  • Your system is configured to spin up a new angular app, if not then just follow this link from the official docs.

Let’s roll!

About the angular internationalization

Angular internationalization

Angular supports multi-languages natively via angular i18n library, which brings localizing the angular app into different versions of locales. Using this we can translate our app content from one language to another, building versions of the app with different languages for different locales. This is generally tricky to configure and takes a lot of time and effort. But this is great if you don’t want to depend on third-party packages like ngx-translate.

The multilingual support is achieved by marking the content of HTML with i18n attribute. Then creating XML based translations files with content translations and other translations aids. Configuring the angular.json file with the required language configuration to run in different locales of the region and then deploying compiling the app to different locales with different languages. Each language results in new build with that specific language content.

This is a lot of work and it doesn’t support many other things that we as developers found it useful. Like the feature to switch your site content from one language to another on the fly, without actually compiling and creating a new build. The more languages your angular app supports the more number of builds it will create resulting in consuming more space in your cloud or wherever you have hosted your app.

Although we have solutions to every problem related to this, but not every solution is easy and less time-consuming. That’s why we are using the ngx-translate library. This internally implements the angular internationalization feature in a lot cleaner way. It also paves a way for developers to fine-tune their angular apps without too much hassle. And, this doesn’t need to add a new build to your app every time you add a new language you just have to add the translations in a JSON file and voila that translations will be available to every build of your app.

Let’s code now

Follow the commands or you can just get the repo from this.

Create a new angular app by this command at your preferred location –

ng new yourAngularApp

Here ‘yourAngularApp‘ is the name of the angular app, feel free to change it. Let the command do its work, prompted for styles – choose CSS and when prompted for needing routing – choose no.

Directory structure of the app

Next install the NGX-translate package from the NPM by running this command –

npm install @ngx-translate/core --save

There are many different parts of NGX-translate. We need not to look at all of them, we are just going for the basics here. To load translations from different files we need a loader. By default there is no loader, we have to install it by this command –

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

We can also create our custom loader, but we are going with this one for simplicity sakes. Once installed let’s update the root NgModule of our angular app i.e. app.module.ts to this –

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";
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
},
defaultLanguage: 'en',
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}

Here in the above config of the TranslateModule, we have also enabled the default language of the app. This means whenever the app loads by default the language will be set to ‘en‘ that means English. You can set it to any language you are familiar with just follow the language short form.

Creating the language specific JSON files

The HttpLoaderFactory or TranslateLoader decides the location of JSON files. By default, location for such files are at /src/assets/i18n/, you can change it your liking. To change this location update the TranslateLoader function in the app.module.ts file –

export function createTranslateLoader(http: HttpClient) {    return new TranslateHttpLoader(http, './assets/i18n/', '.json');}

I am sticking to the default one.

Language specific JSON files location

Initializing the TranslateService in the app

Once, we have the location for the language files, we can begin marking the text in the HTML. To mark the text we have different options from the library. We have string interpolation using pipes and property binding, both can be customized to our needs. I have refactored the app.component.html file to my liking, you can also update it your liking.

Via Interpolation

Inside the HTML file add string interpolation like this –

<h1>{{'LANDING.LINE1' | translate}}</h1>

This “LANDING.LINE1” is the context from the language JSON file. Basically in the JSON file you create a object with key-value pairs. We traverse this object in HTML files using the translate service. Therefore, the above line tells the service to fetch the value of the “LANDING” object with key “LINE1”.

Via Property

Inside the HTML file add this –

<h1 [translate]="'LANDING.PROPERTY.LINE'"></h1>

The traversing of the JSON object will remain the same just the way has changed. Here we are binding this with property of the h1 tag.

JSON content

We created two JSON files, one for English and another for French. Populate the en.json file with content –

{
  "LANDING": {
    "LINE1": "Localization Demo in Angular using ngx-translate",
    "LINE2": "Testing NGX-translate",
    "LINE3": "Greetings everyone! I am Shubhrank Rastogi",
    "PROPERTY": {
      "LINE": "Translating using property binding"
    }
  }
}

And populate the fr.json content with this content –

{
  "LANDING": {
    "LINE1": "Démo de localisation en angulaire avec ngx-translate",
    "LINE2": "Test de NGX-translate",
    "LINE3": "Salutations à tous! Je suis Shubhrank Rastogi",
    "PROPERTY": {
      "LINE": "Traduction à l'aide de la liaison de propriété"
    }
  }
}

Populate the app.component.html file with this content –

<div class="interpolation-content">
  <hr>
  <h1>{{'LANDING.LINE1' | translate}}</h1>
  <h2>{{'LANDING.LINE2' | translate}}</h2>
  <h2>{{'LANDING.LINE3' | translate}}</h2>
  <hr>
</div>
<div class="property-content">
  <h1 [translate]="'LANDING.PROPERTY.LINE'"></h1>
  <hr>
</div>

You will see this result –

Angular app

Great! Your app is now fetching content from the JSON files but we just can’t change the language as of now. So, let’s do that.

Language toggle button

Add this snippet right below the above HTML code –

<ng-container *ngFor="let language of languageList">
  <div class="lang-links">
    <a (click)="changeLang(language.code)">
      <button class="button">{{language.label}}</button>
    </a>
  </div>
</ng-container>

Update the content of app.component.ts file with this –

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 {
  title = 'Ang10-NGX-translate';
  languageList = [
    {code: 'en', label: 'English'},
    {code: 'fr', label: 'French'}
  ];

  constructor(private translate: TranslateService) {
    translate.setDefaultLang('en');
  }

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

Output will be like this –

Angular app with the toggle language button

Now, click on the “French” language button and see the magic happens!

Same app with French language content

This is how we change the language of the app on the fly. No compilation and no creation of the build files for this. All is handle via the ngx-translate service.

On clicking on the button we are actually hitting a method named changeLang() which is accepting an argument lang and is setting the argument to use() method of the translateService. This is how we are changing the language of the app.

Congratulations you have successfully created an angular app that supports two language – FR and EN. If you want to add another just create another JSON file and put the translating content into it. Just make sure all the keys among the objects of these files remain same.

For more details and in depth study visit ngx-translate official docs.

Note : I have used some CSS also for aligning the content and designing those buttons. Feel free to use your imagination here.

Takeaways –

  • Little glimpse of the angular i18n feature
  • Comparison of angular native i18n library with third party ngx-translate library
  • How to setup a angular app with ngx-translate library and how to configure the library to use it.

That’s all for now folks. I hope you have learned something from this blog. If you liked it then please hit the thumbs up and share it with your friends, family or colleagues. Also, please help me improve by giving healthy feedback (below comments). Follow me to get updates on more interesting blogs.

This image has an empty alt attribute; its file name is blog-footer.jpg


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK