String Translate in Multi-language in our angular application.

In this article, we discuss how to translate text in multi-language in our angular application.
We need to install “ngx-translate” module for language translation.

npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save

After install module we need to import “TranslateModule” from the “ngx-translate”
also we have import TranslateHttpLoader to load translations from “/assets/i18n/[lang].json” we need to create langage file in “assets/i18n/” with langage code with json file name.

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

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

import {HttpClient, HttpClientModule} from '@angular/common/http';
import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient);

  imports:      [ 
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
    }) ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
export class AppModule { }

Let’s create “en.json” file for Load english language.

  "APP": {
    "TITLE": "Hello First example For Language Translate",
    "SELECT": "Change language"

we need to import “TranslateService” for set the langage in our compoent where we use to translate string value in diffrent lamguage.

setDefaultLang(lang: string): Sets the default language to use.
addLangs(langs: Array): Add new languages.

      <h2>{{ 'APP.TITLE' | translate }}</h2>
        {{ 'APP.SELECT' | translate }}
        <select #langSelect (change)="translate.use(langSelect.value)">
          <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option>

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

  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
export class AppComponent  {
  name = 'Angular';
  constructor(public translate: TranslateService) {

    translate.addLangs(['en', 'fr','de']);

    const browserLang = translate.getBrowserLang();
    translate.use(browserLang.match(/en|fr|de/) ? browserLang : 'en');


Below is the running embedded code for multi-language string translate.

Spread the love