Angular 9 Internationalization/Localization with ngx-translate Tutorial and Example

Angular 9 Internationalization/Localization with ngx-translate Tutorial and Example

In this tutorial, we'll see by example how to make your Angular 9 app available in multiple languages (English and French) using ngx-translate, the internationalization (i18n) and localization library for Angular.

Using ngx-translate for Internationalizating your Angular 9 App

The ngx-translate package makes it easy to translate your Angular app in multiple languages.

In this tutorial. we'll learn how to:

  • Create an Angular 9 project with Angular CLI,
  • Set up internationalization with english and french languages using ngx-translate

You will need to have the following prerequisites:

That's all, let's get started!

Creating the Angular 9 Project

Let's start by creating our Angular 9 project using Angular CLI:

ng new angular-9-i18n --style css --routing false

Next, navigate to your project's folder and run the development server:

cd angular-9-i18n
ng serve -o

Add Internationalization to Angular 9 Apps with ngx-translate

Let’s now implement internationalization in our Angular 9 application.

We can add internationalization (i18n) in Angular 9 via the ngx-translate package.

We'll see how to enable users to switch between multiple languages using various translation files imported from by ngx-translate.

Let's get started by installing the required dependencies using the following command:

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

Next, add the following translations files:

cd src/assets/
mkdir i18n 
cd i18n
touch en.json
touch fr.json

Open the src/assets/i18n/en.json file and the following JSON content:

{
   "appTitle": "Angular 9 Example",
   "appText": "Welcome to our app!"
}

Next, open the src/assets/i18n/fr.json:

{
   "appTitle": "Exemple d'Angular 9",
   "appText": "Bienvenue dans notre application!"
}

Now that we have created the translation files, we need to import the ngx-translate module and loading the translations by adding the following code in the src/app/app.module.ts file:

import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { NgModule } from '@angular/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

export function TranslationLoaderFactory(http: HttpClient) {
      return new TranslateHttpLoader(http);
}

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

We import HttpClient with TranslateHttpLoader to load translation files using this factory method:

export function TranslationLoaderFactory(http: HttpClient) {
      return new TranslateHttpLoader(http);
}

Next, we import TranslateModule and provide the loader factory:

TranslateModule.forRoot({
      loader: {provide: TranslateLoader, useFactory: TranslationLoaderFactory, deps: [HttpClient]}
})

Next, open the src/app/app.component.html file and update it as follows:


<h1>
  appTitle
</h1>
<div>
  <button (click)="useLanguage('en')">English</button>
  <button (click)="useLanguage('fr')">French</button>
</div>

<p>appText: </p>

Next, we need to implement the useLanguage() method in our App component.

Open the src/app/app.component.ts file and update it as folows:

import { Component, OnInit, Inject, PLATFORM_ID, Optional } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
 title = 'angular-9-i18n';
 langs = ['en', 'fr'];

 constructor(private translateService: TranslateService) {}

 public ngOnInit(): void {
   let browserlang = this.translateService.getBrowserLang();
   if (langs.indexOf(browserLang) > -1) {
     this.translateService.setDefaultLang(browserlang);
   } else {
     this.translateService.setDefaultLang('en');
   }
 }


 public useLanguage(lang: string): void {
   this.translateService.setDefaultLang(lang);
 }
}

We simply inject TranslateService in our component and use the getBrowserLang and setDefaultLang methods to get the default browser language and set the default language.

Now, that we have implemented internationalization in our Angular 9 app, let's run it using the following command:

ng serve -o

Conclusion

In this tutorial, we've created an Angular 9 app with internationalization using ngx-translate.



Create Angular 17 Project
Building a Password Strength Meter in Angular 17
Angular 17 Password Show/Hide with Eye Icon
Angular 17 tutoriel
Angular Select Change Event
Angular iframe
Angular FormArray setValue() and patchValue()
Angular Find Substring in String
Send File to API in Angular 17
EventEmitter Parent to Child Communication
Create an Angular Material button with an icon and text
Input change event in Angular 17
Find an element by ID in Angular 17
Find an element by ID from another component in Angular 17
Find duplicate objects in an array in JavaScript and Angular
What is new with Angular 17
Style binding to text-decoration in Angular
Remove an item from an array in Angular
Remove a component in Angular
Delete a component in Angular
Use TypeScript enums in Angular templates
Set the value of an individual reactive form fields
Signal-based components in Angular 17
Angular libraries for Markdown: A comprehensive guide
Angular libraries for cookies: A comprehensive guide
Build an Angular 14 CRUD Example & Tutorial
Angular 9 Components: Input and Output
Angular 13 selectors
Picture-in-Picture with JavaScript and Angular 10
Jasmine Unit Testing for Angular 12
Angular 9 Tutorial By Example: REST CRUD APIs & HTTP GET Requests with HttpClient
Angular 10/9 Elements Tutorial by Example: Building Web Components
Angular 10/9 Router Tutorial: Learn Routing & Navigation by Example
Angular 10/9 Router CanActivate Guards and UrlTree Parsed Routes
Angular 10/9 JWT Authentication Tutorial with Example
Style Angular 10/9 Components with CSS and ngStyle/ngClass Directives
Upload Images In TypeScript/Node & Angular 9/Ionic 5: Working with Imports, Decorators, Async/Await and FormData
Angular 9/Ionic 5 Chat App: Unsubscribe from RxJS Subjects, OnDestroy/OnInit and ChangeDetectorRef
Adding UI Guards, Auto-Scrolling, Auth State, Typing Indicators and File Attachments with FileReader to your Angular 9/Ionic 5 Chat App
Private Chat Rooms in Angular 9/Ionic 5: Working with TypeScript Strings, Arrays, Promises, and RxJS Behavior/Replay Subjects
Building a Chat App with TypeScript/Node.js, Ionic 5/Angular 9 & PubNub/Chatkit
Chat Read Cursors with Angular 9/Ionic 5 Chat App: Working with TypeScript Variables/Methods & Textarea Keydown/Focusin Events
Add JWT REST API Authentication to Your Node.js/TypeScript Backend with TypeORM and SQLite3 Database
Building Chat App Frontend UI with JWT Auth Using Ionic 5/Angular 9
Install Angular 10 CLI with NPM and Create a New Example App with Routing
Styling An Angular 10 Example App with Bootstrap 4 Navbar, Jumbotron, Tables, Forms and Cards
Integrate Bootstrap 4/jQuery with Angular 10 and Styling the UI With Navbar and Table CSS Classes
Angular 10/9 Tutorial and Example: Build your First Angular App
Angular 9/8 ngIf Tutorial & Example
Angular 10 New Features
Create New Angular 9 Workspace and Application: Using Build and Serve
Angular 10 Release Date: Angular 10 Will Focus on Ivy Artifacts and Libraries Support
HTML5 Download Attribute with TypeScript and Angular 9
Angular 9.1+ Local Direction Query API: getLocaleDirection Example
Angular 9.1 displayBlock CLI Component Generator Option by Example
Angular 15 Basics Tutorial by Example
Angular 9/8 ngFor Directive: Render Arrays with ngFor by Example
Responsive Image Breakpoints Example with CDK's BreakpointObserver in Angular 9/8
Angular 9/8 DOM Queries: ViewChild and ViewChildren Example
The Angular 9/8 Router: Route Parameters with Snapshot and ParamMap by Example
Angular 9/8 Nested Routing and Child Routes by Example
Angular 9 Examples: 2 Ways To Display A Component (Selector & Router)
Angular 9/8 Tutorial: Http POST to Node/Express.js Example
Angular 9/8 Feature and Root Modules by Example
Angular 9/8 with PHP: Consuming a RESTful CRUD API with HttpClient and Forms
Angular 9/8 with PHP and MySQL Database: REST CRUD Example & Tutorial
Unit Testing Angular 9/8 Apps Tutorial with Jasmine & Karma by Example
Angular 9 Web Components: Custom Elements & Shadow DOM
Angular 9 Renderer2 with Directives Tutorial by Example
Build Progressive Web Apps (PWA) with Angular 9/8 Tutorial and Example
Angular 9 Internationalization/Localization with ngx-translate Tutorial and Example
Create Angular 9 Calendar with ngx-bootstrap datepicker Example and Tutorial
Multiple File Upload with Angular 9 FormData and PHP by Example
Angular 9/8 Reactive Forms with Validation Tutorial by Example
Angular 9/8 Template Forms Tutorial: Example Authentication Form (ngModel/ngForm/ngSubmit)
Angular 9/8 JAMStack By Example
Angular HttpClient v9/8 β€” Building a Service for Sending API Calls and Fetching Data
Styling An Angular 9/8/7 Example App with Bootstrap 4 Navbar, Jumbotron, Tables, Forms and Cards

βœ‹If you have any questions about this article, ask them in our GitHub Discussions πŸ‘ˆ community. You can also Gitter

βœ‹ Want to master Angular 14? Read our angular tutorial and join our #DailyAngularChallenge where we learn to build components, directives, services, pipes and complete web, mobile, and desktop applications with latest Angular version.

βœ‹ Make sure to join our Angular 14 Dev Community πŸ‘ˆ to discuss anything related to Angular development.

❀️ Like our page and subscribe to our feed for updates!

Find a list of emojis to copy and paste