We fasten ngx-translate in Angular application. Practical Walkthrough

A practical step-by-step instruction on how to fasten dynamic localization (the ability to select languages) in an Angular 4+ web application using @ ngx-translate / core .







In principle, you can find publications on a similar topic, the documentation of this library may be enough, but I wanted to systematize this instruction for more convenient use. Such a bookmark is in the piggy bank of a novice Angular developer. At the end of the article there is a link to an open repository with an example.













Why exactly ngx-translate



I want to make a reservation right away, this is an instruction for using a specific library. We will not talk about alternatives, that the angular has its own i18n localization. If only because with the dynamic change of language there are questions.







What do we get at the exit





 // en.json { Common: { Yes: "Yes" } }
      
      





This will allow you to group keys / values ​​and somehow organize a json file with localization. For large projects it is quite useful.









Customize



  1. We create or take a ready angular project. The version of the angular is 4+, but it is better of course as fresh as possible.







  2. Install the necessary libraries:









 npm install @ngx-translate/core --save npm install @ngx-translate/http-loader --save @biesbjerg/ngx-translate-extract --saveDev
      
      





The @ngx-translate/http-loader



library is needed so that we can read localization data from *.json



files. You can live without it, but then you will have to completely write the storage and loading of localization data yourself. This approach is suitable for those who have localization data (or simply all translated texts) already stored somewhere.



The @biesbjerg/ngx-translate-extract



library is optional, but pretty useful. It allows you to collect forgotten localization keys by application code and update localization files. Using it is very convenient to process such a scenario: add a new language and just run the command from this library. As a result, an empty file for the new language will be filled with the entire structure of the keys and some default values. An example will be below.


  1. Import the library in the main module:


 @NgModule({ imports: [ TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient], }, useDefaultLang: false, }) ], }) export class AppModule { }
      
      





The HttpLoaderFactory



present in the library HttpLoaderFactory



, it can be described directly in the same file, it is modest in size.







 export function HttpLoaderFactory(http: HttpClient): TranslateLoader { return new TranslateHttpLoader(http, './assets/locale/', '.json'); }
      
      





This is where we indicate the path to the localization files. If they are stored somehow separately, or even differently in different environments - change this code to use environment.ts



for example.







  1. In principle, this is enough for the basic settings, but we will take another additional step - error handling when the key is not found.


To do this, add one more field to the configuration (immediately after specifying loader):







 missingTranslationHandler: { provide: MissingTranslationHandler, useClass: MissingTranslationService },
      
      





And of course, you need to create the implementation of this handler in a separate file:







 export class MissingTranslationService implements MissingTranslationHandler { handle(params: MissingTranslationHandlerParams) { return `WARN: '${params.key}' is missing in '${params.translateService.currentLang}' locale`; } }
      
      





  1. Add storage of available languages. In the simple case, it’s convenient to put them in environment.ts





 locales: ['en', 'ru'], defaultLocale: 'en',
      
      





  1. For the service to start working, it must be initialized in the AppComponent file when loading the application:


 @Component({...}) export class AppComponent implements OnInit { constructor(private translateService: TranslateService) {} ngOnInit(): void { this.translateService.use(environment.defaultLocale); } }
      
      





  1. Add the files en.json



    and ru.json



    (according to what is indicated in the list of available languages). Add some base field so that it is valid json.


When these steps are taken, the service will begin to work.







We use the service



HTML markup



Everything is simple here. The library offers pipe translate



, we just apply it in the markup for certain keys.







 <label>{{ 'LANGUAGES.TITLE' | translate }}</label>
      
      





Notice that I use the attached properties here, the json structure that I spoke about at the beginning.



Parameters are also supported, look at them please in the documentation @ ngx-translate / core . Using parameters, you can implement something like string interpolation.


In component code



 this.translateService.get(['KEY1', 'KEY2'])) .subscribe(translations => { console.log(translations['KEY1']) console.log(translations['KEY2']) });
      
      





This is a reliable way if you are normal with Observable and RxJs.

If not, there is a way:







 this.translateService.instant('Key')
      
      





This method works well, but at the initialization stage of the application (for example, ngOnInit AppComponent) the data for it may not yet be loaded. Be careful.


Support for .json files



In the end, I want to show how to use the ngx-translate-extract



utility. Just execute the command ngx-translate-extract -i ./src -o src/assets/locale/*.json --sort --format namespaced-json



in the console. This command will start the analysis of application files, markup and timecode code. All the keys found in the markup and other code will fall into .json for all languages, the existing keys and their values ​​will remain untouched, except that the order may change.







For convenience, I am adding this as a script in package.json







 "scripts": { "ng": "ng", "start": "ng serve", "update-locale": "ngx-translate-extract -i ./src -o src/assets/locale/*.json --sort --format namespaced-json" },
      
      





Everything that I described can be found assembled together in an open repository: valentinkononov / ngx-translate-angular







I hope the material will be useful! Write code with pleasure, choose convenient libraries and make useful projects!








All Articles