How to Implement Internationalization in Angular Using i18n Tools?

ARYA N K | November 21, 2022

 How to Implement Internationalization in Angular Using i18n Tools?

Any current application must have internationalization which is a compulsory feature. The I18n, often known as internationalization, is the process of adding multiple language support to our app to increase its accessibility to a wider audience.The application can now target any language in the world thanks to internationalization.

Translation of the application into a specific language is called localization. The app requires to be internationalized before it can be localized. An application to render in a specific local language. Angular provides full approval for the localization and internationalization features.


To add the package to your application, use the command shown below:

npm install @ngx-translate/core@13.0.0

Include your translation files as assets and load them to use the TranslateHttpLoader, which is available in a separate npm package, is probably the most popular method for loading translations.

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

Now import the TranslateModule in your AppModule:


src/app/app.module.ts


    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpClientModule, HttpClient } from '@angular/common/http';
    import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
    import { TranslateHttpLoader } from '@ngx-translate/http-loader';
    import { AppComponent } from './app.component';
    export function HttpLoaderFactory(http: HttpClient) {
        return new TranslateHttpLoader(http);
    }
    @NgModule({
        declarations: [ AppComponent ],
        imports: [
            BrowserModule,
            HttpClientModule,
            TranslateModule.forRoot({
                loader: {
                    provide: TranslateLoader,
                    useFactory: HttpLoaderFactory,
                    deps: [HttpClient]
                }
            })
        ],
        providers: [],
        bootstrap: [AppComponent]
    })
    export class AppModule { }

    

Using Translation Files

The /assets/i18n/ folder of your project must contain a folder named "lang.json," where "lang" denotes the language of the file you are using for translations. This is required to generate the translation loader. For English, this file might be titled en.json, for instance.

The translated text is stored in the translation file as a JSON object with key-value pairs, where the key identifies the translated text and the value is the translated text in the language specified in the file.


src/assets/i18n/en.json


    {
        "welcomeMessage": "Thanks for joining, {{ firstName }}! It's great to have you!",
        "login": {
            "username": "Enter your user name",
            "password": "Password here"
        }
    }            

    

You can organize your translations as you want by using the value, which can also be another object. Double curly brackets around a variable name in the text of your translation value can also be used to later interpolate strings dynamically into your translations.


Accessing Translations

You should initialize just a few properties in the TranslateService before your application can access these translations. It should probably be done in your bootstrapped AppComponent.


src/app/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 {
        constructor(translate: TranslateService) {
            translate.addLangs(['en', 'klingon']);
            translate.setDefaultLang('en');
            translate.use('en');
        }
    }

    

Start by translating. The service is informed which languages are available to use for translations by addLangs([]).

You can specify a backup set of translations to utilize in the event that the current language's translations are not available by using the translate.setDefaultLang('en') method. The method translate.use('en') instructs the service to translate in the current language.

The language you wish to use for all of these is the parameter, and it should be the same as the names of the JSON files that define the translations for those languages.


Using TranslateService

Using the service, there are two methods to get your translations.

The first, and recommended, method is to use:

get(key: string|Array< string>, interpolateParams?: Object)`

The second method is to use:

instant(key: string|Array< string>, interpolateParams?: Object)`

Remember, we told the service to use en as the current lang, so all translation results will come from en.json initially.


src/app/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 {
        user!: { firstName: string; lastName: string; };
        welcome!: string;
        usernameLabel!: string;
        passwordLabel!: string;
        constructor(translate: TranslateService) {
            translate.addLangs(['en', 'klingon']);
            translate.setDefaultLang('en');
            translate.use('en');
        }
        
        ngOnInit() {
            // hardcoded example
            this.user = { firstName: 'Sammy', lastName: 'Shark' };
            // synchronous. Also interpolate the 'firstName' parameter with a value.
            this.welcome = this.translate.instant('welcomeMessage', { firstName: this.user.firstName });
            // asynchronous - gets translations then completes.
            this.translate.get(['login.username', 'login.password'])
            .subscribe(translations => {
                this.usernameLabel = translations['login.username'];
                this.passwordLabel = translations['login.password'];
            });
        }
    }
                  
    

The use(lang: string) function on the TranslateService can be called to set the current language, whether through a pick box, URL route, or other way. You can also build your own mechanism in your application to switch between languages.


Using TranslatePipe

The key to the translation you need is the input into the pipe. An object that defines any interpolation strings that the translation is expecting is the optional parameter.


src/app/app.component.html


    < p> {{ 'welcomeMessage' | translate: user }} < /p>
    < input type="password" placeholder=" {{ 'login.password' | translate }} ">
        
    

In this blog, we learned how to use i18n tools to internationalize our Angular app. Localization was also used in our Angular application. We can extend the reach of our app to a worldwide audience by serving our app in a different language.



As a leading Angular application company at Sanesquare Technologies, We offer exceptional Angular Application Development Services to meet our client's requirements. If you need assistance or have queries, feel free to contact us.

Does your Project Demand Expert Assistance?

Contact us and let our experts guide you and fulfil your aspirations for making the project successful

contactUs_img