Ngx-Translate In Angular Allows You To Switch Between Many Languages

Integration of multiple language support in Angular application tutorial; In this tutorial, you will learn how to add the Internationalization or i18n in Angular app by utilizing the ngx-translate plugin.

Step 1 – Create Angular Application
  • npm install -g @angular/cli
  •  ng new angular-ngx-translate
Step 2 – Install the HTTP Loader and Ngx Translate plugins.
  • npm install @ngx-translate/core –save
  • npm install @ngx-translate/http-loader –save
Step 3 – App Module Update

We must import the relevant packages into the App Module of our application when they have been installed.

Open the app.module.ts file and update it as shown:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
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 httpTranslateLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: httpTranslateLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Step 4 – Setup Translation JSON Files

This article contains a list of all i18n language codes.

The key-value pair JSON object in the src/assets/i18n/en.json file for English (en).

{
    "TITLE": "Welcome prinkesha lathidadiya, your profile details are",
    "USER_INFORMATION":{
        "NAME":"Name",
        "WORKING_PROFILE":"Working Profile",
        "AGE":"Age",
        "EDUCTION_DETAILS":"Eduction Details",
        "ADDRESS_DETAILS":"Address Details",
        "PHONE_NUMBER":"Phone Number",
        "EMAIL_ADDRESS":"Email Address",
        "RELEVANT_EXPERIENCE":"Relevant Experience"
    }
}

The key-value pair JSON object in the src/assets/i18n/es.json file for Spanish (es).

{
    "TITLE": "Bienvenido prinkesha lathidadiya los detalles de su perfil son",
    "USER_INFORMATION":{
        "NAME":"Nom",
        "WORKING_PROFILE":"Profil de travail",
        "AGE":"edad",
        "EDUCTION_DETAILS":"Detalles de educación",
        "ADDRESS_DETAILS":"Détails de l'adresse",
        "PHONE_NUMBER":"Numéro de téléphone",
        "EMAIL_ADDRESS":"Adresse e-mail",
        "RELEVANT_EXPERIENCE":"Expérience pertinente"
    }
}

The key-value pair JSON object in the src/assets/i18n/fr.json file for French (fr).

{
    "TITLE": "Bienvenue prinkesha lathidadiya les détails de votre profil sont",
    "USER_INFORMATION":{
        "NAME":"Nombre",
        "WORKING_PROFILE":"Perfil de trabajo",
        "AGE":"âge",
        "EDUCTION_DETAILS":"Détails de l'éducation",
        "ADDRESS_DETAILS":"Detalles de dirección",
        "PHONE_NUMBER":"Número de teléfono",
        "EMAIL_ADDRESS":"Dirección de correo electrónico",
        "RELEVANT_EXPERIENCE":"Experiencia relevante"
    }
}
Step 5 – Translate Pipe and Language Switch can be used to update HTML.

The TranslateModule includes a translate pipe that may be included in an HTML template to translate the specified key.

Now, open the app.component.html file and update it with the following code:

<section class="main">
  Select Language :
  <select #selLang (change)="changeLanguageTo(selLang.value)">
    <option *ngFor="let language of change.getLangs()" [value]="language">{{ language }}</option>
  </select>

  <h1>{{'TITLE' | translate: user}}</h1>
  <ul>
    <li>
      <b>{{'USER_INFORMATION.NAME' | translate}}</b> : Prinkesha lathidadiya
    </li>
    <li>
      <b>{{'USER_INFORMATION.WORKING_PROFILE' | translate}}</b> : Web developer
    </li>
    <li>
      <b>{{'USER_INFORMATION.AGE' | translate}}</b> : 24
    </li>
    <li>
      <b>{{'USER_INFORMATION.EDUCTION_DETAILS' | translate}}</b> : Mca
    </li>
    <li>
      <b translate="USER_INFORMATION.ADDRESS_DETAILS"></b> : c:1001 vastu pooja heights
    </li>
    <li>
      <b>{{'USER_INFORMATION.PHONE_NUMBER' | translate}}</b> : 345.678.123x.45645
    </li>
    <li>
      <b>{{'USER_INFORMATION.EMAIL_ADDRESS' | translate}}</b> : hendy@gmail.com
    </li>
    <li>
      <b>{{'USER_INFORMATION.RELEVANT_EXPERIENCE' | translate}}</b> :3.5 Years
    </li>
  </ul>

</section>
Step 6 –  Inject TranslateService in Component

Now, open the app.component.ts file to import the TranslateService and inject it in the component’s constructor.

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title!: string;
  emailId!: string;
  user!: { loginUser: string };

  constructor( public change: TranslateService ) {
    change.addLangs(['en', 'es', 'fr']);
    change.setDefaultLang('en');   // default language
    this.getTitle();
  }
  getTitle() {
    this.change.get(['TITLE', 'USER_INFORMATION.EMAIL_ADDRESS'])
      .subscribe(change => {
        this.title = change['TITLE'];
        this.emailId = change['USER_INFORMATION.EMAIL_ADDRESS'];
      });
  }
  changeLanguageTo(lang: string) {
    this.change.use(lang);
  }
}

The getTitle() method uses the get() method to retrieve the translated data, which it then assigns to title and emailId within the class.

Step 7 –Run Application

Serve the application now to observe how the translation feature works. To execute the application and open it in the default browser, type the following command:

ng -o serve

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories