In this article, we will figure out how to make our Angular application accessible in various languages using localization. We will make an Angular application and design it to serve the substance in two different languages.
Using this article, we will essay set us localization in our Angular Application.
So, if we want to implement the Localization in the Angular Application, then we need to perform the following steps
Step 1:-
Create an Angular application using this command
ng new localization
Step 2:-
Add the following package to your application
npm i @ngx-translate/core npm i @ngx-translate/http-loader
Step 3:-
Add the following Command in your app.component.ts file
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 = 'local-demo'; constructor(public translate: TranslateService) { translate.addLangs(['en-US', 'fr-FR']); translate.setDefaultLang('en-US'); const browserLang = translate.getBrowserLang(); translate.use(browserLang.match(/fr|fr-FR/) ? 'fr-FR' : 'en-US'); } }
Step 4:-
Add the following command in your app. component.html file
<div> <h2>{{ 'HOME.TITLE' | translate }}</h2> <label> {{ 'HOME.SELECT' | translate }} <select #langSelect (change)="translate.use(langSelect.value)"> <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option> </select> </label> </div>
Step 5:-
Add the following command in your app. module.html file
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import { AppComponent } from './app.component'; import {HttpClient, HttpClientModule} from '@angular/common/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; export function HttpLoaderFactory(httpClient: HttpClient) { return new TranslateHttpLoader(httpClient); } @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step 6:-
Add en-US.json and fr-FR.json files in your assent folder.
And then add the following command in your en-US.json file.
{ "HOME": { "TITLE": "Hello Angular with ngx-translate!", "SELECT": "Change language" } }
And then add the following command in your fr-FR.json file.
{ "HOME": { "TITLE": "Bonjour Angular avec ngx-translate !", "SELECT": "Changer la langue" } }
Output:-