Angular Multiple Language Support using Internationalization (i18n)
Wall Script
Wall Script
Tuesday, October 13, 2020

Angular Multiple Language Support using Internationalization (i18n)

Modern web and mobile user experiences is a worldwide thing. Localization of your application (supporting multiple languages) will help you to reach worldwide people. Angular is offering Internationalization(i18n) plugins to enrich your application with multiple languages. In this post I will discuss the implementation with lazy loading design pattern with supporting dynamic content. Take a quick look at the live demo and choose the language.

Angular Translate


Live Demo

GitHub Source

Video Tutorial


Getting Started with Lazy Loading Angular Project

Lazy loading is a modern design pattern this works based on Angular modules. Create an Angular Project
Use ng command to generate the project.
$ng new angular-translate

Create pages and services folder.
Angular Translate

Generate Home Page
Create a home page using a ng command.
angular-translate$ ng generate component pages/home
CREATE src/app/pages/home/home.component.scss (0 bytes)
CREATE src/app/pages/home/home.component.html (19 bytes)
CREATE src/app/pages/home/home.component.spec.ts (614 bytes)
CREATE src/app/pages/home/home.component.ts (268 bytes)
UPDATE src/app/app.module.ts (473 bytes)

Generate Home Module
angular-translate$ ng generate module pages/home
CREATE src/app/pages/home/home.module.ts (188 bytes)

Generate Settings Page
angular-translate$ ng generate component pages/home
CREATE src/app/pages/settings/settings.component.scss (0 bytes)
CREATE src/app/pages/settings/settings.component.html (19 bytes)
CREATE src/app/pages/settings/settings.component.spec.ts (614 bytes)
CREATE src/app/pages/settings/settings.component.ts (268 bytes)
UPDATE src/app/app.module.ts (473 bytes)

Generate Settings Module
angular-translate$ ng generate module pages/settings
CREATE src/app/pages/settings/settings.module.ts (188 bytes)

File Structure
You will find the auto generated files in the following file structure. And manually create a routes file for Home and Settings pages.
Angular translate


home.routes.ts
Home route lazy loading configuration file and import the home component.
import { Route } from '@angular/router';
import { HomeComponent } from './home.component';

export const HomeRoutes: Route[] = [
{
path: '',
component: HomeComponent,
},
];


settings.routes.ts
Follow the same.
import { Route } from '@angular/router';
import { SettingsComponent } from './settings.component';

export const SettingsRoutes: Route[] = [
{
path: '',
component: SettingsComponent,
},
];


Routes Configuration


home.module.ts
Connect routes with RouterModule.
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HomeComponent } from './home.component';
import { HomeRoutes } from './home.routes';

@NgModule({
declarations: [HomeComponent],
exports: [HomeComponent],
imports: [CommonModule, RouterModule.forChild(HomeRoutes)],
})
export class HomeModule {}



settings.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SettingsComponent } from './settings.component';
import { SettingsRoutes } from './settings.routes';

@NgModule({
declarations: [SettingsComponent],
exports: [SettingsComponent],
imports: [CommonModule, RouterModule.forChild(SettingsRoutes)],
})
export class SettingsModule {}


app.component.html
Clean up the default code execept the following router-outlet tag.
<router-outlet></router-outlet>


app.module.ts
Remove auto imported Home and Settings components.
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
declarations: [AppComponent],
imports: [HttpClientModule, BrowserModule, AppRoutingModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}


app-routing.module.ts
App routes connect with Home and Setting moudles. You have to sepcify the page path name. Here I have configure home page is default page with empty path value.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
{
path: '',
loadChildren: () =>
import('./pages/home/home.module').then((m) => m.HomeModule),
},
{
path: 'settings',
loadChildren: () =>
import('./pages/settings/settings.module').then((m) => m.SettingsModule),
},
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}


Restart Angular Server 
You can access http://localhost:4200/ and http://localhost:4200/settings
$ng serve

Install Translate Plugin
$npm install @ngx-translate/core

$npm install @ngx-translate/http-loader

Language Assets
Create language files in JSON format.
Angular translate

en.json
English version language file.
{
"home": {
"title": "Home page",
"welcome_text": "Your welcome text"
},
"settings": {
"title": "Settings page"
}
}


fr.json
French version.
{
"home": {
"title": "Page d'accueil",
"welcome_text": "Faites tomber les gens amoureux de vos idées.",
},
"settings": {
"title": "Page Paramètres"
}
}


Configure with i18n files.

app.module.ts 
Import translate modules and configured with language assets.
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

export function rootLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
}

@NgModule({
declarations: [AppComponent],
imports: [
HttpClientModule,
BrowserModule,
AppRoutingModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: rootLoaderFactory,
deps: [HttpClient],
},
}),
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}



home.module.ts
Import TranslateModule. Follow the same for settings.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { HomeComponent } from './home.component';
import { HomeRoutes } from './home.routes';

@NgModule({
declarations: [HomeComponent],
exports: [HomeComponent],
imports: [CommonModule, RouterModule.forChild(HomeRoutes), TranslateModule],
})
export class HomeModule {}


Create a TranslateConfig Service 
Generate a service for changing the language type.
$ng generate service services/translateConfig

You will find in services directory.
Angular translate


translate-config.ts 
Here the default language constructed with English(en) language. And changeLanguage method will help you to switch with other supported languages.
import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Injectable({
providedIn: 'root',
})
export class TranslateConfigService {
constructor(private translateService: TranslateService) {
this.translateService.use('en');
}

changeLanguage(type: string) {
this.translateService.use(type);
}
}



Localizing Application

home.component.ts 
Import translateConfig service.
import { Component, OnInit } from '@angular/core';
import { TranslateConfigService } from '../../services/translate-config.service';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
constructor(private translateConfigService: TranslateConfigService) {}

ngOnInit(): void {}
}



home.component.html
Use translate pipe for HTML content with JSON content refernece.
<h1 translate>home.title</h1>
<h2 translate>home.welcome_text</h2>


settings.component.ts
Imported translateConfig service and create a method to change the default language.
import { Component, OnInit } from '@angular/core';
import { TranslateConfigService } from '../../services/translate-config.service';

@Component({
selector: 'app-settings',
templateUrl: './settings.component.html',
styleUrls: ['./settings.component.scss'],
})
export class SettingsComponent implements OnInit {
constructor(private translate: TranslateConfigService) {}

ngOnInit(): void {}

/* Change default language */
changeDefaultLanguage(langType: string){
this.translate.changeLanguage(langType);
}

}



settings.component.html
Button actions for changing languages.
<h4 translate>settings.title</h4>
<div>
<button (click)="changeDefaultLanguage('en')">English</button>
<button (click)="changeDefaultLanguage('fr')">French</button>
<button (click)="changeDefaultLanguage('es')">Spanish</button>
<button (click)="changeDefaultLanguage('te')">Telugu</button>
<button (click)="changeDefaultLanguage('ta')">Tamil</button>
</div>


Dynamic Translation If you have a dynamic content value that comes from the API response like email. Here email is reference key.
{
"home": {
"title": "Home page",
"welcome_text": "Make people fall in love with your ideas.",
"email_text": "Email us at {{email}}"
},
"settings": {
"title": "Settings page"
}
}



Dynamic Translation HTML
Use innerHTML attribute and pass the dynamic content. Eg: Email us at [email protected]
<span [innerHTML]="'home.email_text' | translate: { email: '[email protected]' }"></span>


Multiple Dynamic Translations
You can pass multiple values in the following format.
{
"home": {
"title": "Home page",
"welcome_text": "Make people fall in love with your ideas.",
"email_text": "Email us at {{email}}",
"sum_text": "When the value {{value1}} added to value {{value2}} = "
},
"settings": {
"title": "Settings page"
}
}


home.component.ts
import { Component, OnInit } from '@angular/core';
import { TranslateConfigService } from '../../services/translate-config.service';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
public a = 2;
public b = 1;

constructor(private translateConfigService: TranslateConfigService) {}

ngOnInit(): void {}
}

home.component.html
<span [innerHTML]="'home.sum_text' | translate: { value1: a, value2: b }"></span> {{a+b}}



Download Github project for more understanding.
web notification

0 comments:

mailxengine Youtueb channel
Make in India
X