How to implement localization in Angular 2 Plus

A locale denotes region in which application is running and identifies that region where people speak a particular language.

We will add localization in angular application using ngx-translate/core package. let's understand how to use it step by step.

Step 1: Install ngx-translate/core package in your app using following command.


     npm i @ngx-translate/core

Step 2: Import package in app module 

import { TranslateModule, TranslateLoader } from '@ngx-translate/core';

After this, add TranslateModule in import array of app module as below


TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      },
      defaultLanguage: 'en'
    })

Step 3: Create a folder i18n in assets folder and create seprate json files of your languages as below.

Step 4: Now it's time to add translation for texts where you want to add it.

If you want to add this in html file, you can use as following.


{{'HOME.MESSAGE' | translate}} // here translate is a pipe

// HOME.MESSAGE is denoting keys of your json file as following

{

    "HOME": {

        "MESSAGE": "Some Message"

    }

}

If you want to add translation in component, you can do the same as following.


constructor(
            private translate: TranslateService)
	{}
	
 this.translate.instant('HOME.MESSAGE') 

These are the simple steps to follow and you will have a application with Internationalization, you can publish your app in multiple languages if you need it.

Hope you will find this helpful, write us below to improve article.

Thank you for reading :) Please subscribe our newsletter to get updates for new articles

Leave a comment

your email address will not be published. required fields are marked *

Name *
Email *
Phone