Make a multilingual application in Angular

in #angular6 years ago

Languages


Working as a software developer in Belgium, you always have to keep in mind that half the country speaks a different language than you. For someone with no language learning ability what so ever, this can be challenging to say the least :).

Fortunately, we can relatively easy set up a multilingual application in Angular using json files, which you can give to someone else to translate and add in your project 🙂

I'm starting from a default angular cli template, find out here how to set it up.

ngx-translate


To make this happen, we will use an existing library, ngx-translate.

So let us install this with npm, open a command prompt at the root of the project and run the following commands to install the core module and the httploader.

C:\Projects\MySolution\Demo\hello-world>npm install @ngx-translate/core
C:\Projects\MySolution\Demo\hello-world>npm install @ngx-translate/http-loader



When this is done, we can import these in our app module.

app.module.ts

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

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

@NgModule({
  declarations: [
    AppComponent
  ],

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



As you can see in the code, we first declare a HttpLoaderFactory, that will load the json files from the ./assets/i18n/ folder

in the forRoot() function, we provide our factory to load our translations. Because this also relies on our HttpClient, we have to add it here in 'deps'. Because we provide this in our forRoot function, it won't be necessary to do this in our imports of the translate module in any child module.
Now let us add a subfolder to the assets folder named, you guessed it, i18n. In here add the following files:

en.json

{
  "language":"English",
  "hello":"Hello"
}



nl.json

{
  "language":"Nederlands",
  "hello":"Hallo"
}



fr.json

{
  "language":"Français",
  "hello":"Bonjour"
}



de.json

{
  "language":"Deutsch",
  "hello":"Gutentag"
}



The end result should look like this:

Ok, everything is in place, it's demo time!

Lets first change app.component.html. As you can see, we can now use the translate pipe and provide the key value. This pipe will get the translated value back, based on the currently used language.

app.component.html

<h1>{{ "language" | translate }}</h1>
<p>
  Start editing to see some magic happen :)
</p>



And finally, we need to edit app.component.ts

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 {

  //translations: any;

  constructor(private translateService: TranslateService) {
    this.translateService.setDefaultLang('en');
    this.translateService.use(this.translateService.getBrowserLang());
  }
}



First we set the default language to 'en'.

After that, we call the use function with the browser language. So what will happen when there is no json file defined for the browser language? Like you probably guessed, the default language, 'en' in this case, will be used.

Of course, if you want the user to change languages, you can make a selection and switch languages with the function this.translateService.use('de');

Maybe one last thing to mention. If you need to get the translation in your component without using the filter, there is also a function for that.

this.translateService.get(["hello", "language"]).subscribe((data: any) => {
   this.translations = data;
   });



You can provide an array of keys that you want to translate, and the return object will contain the translations based on the currently active language.

Example


If you have any troubles, you can always let me know or check out the example right here!

I hope you learned something new in this post or I provided you help in any way!

Coin Marketplace

STEEM 0.19
TRX 0.14
JST 0.029
BTC 64156.67
ETH 3169.32
USDT 1.00
SBD 2.53