How To Use ngx-translate with Angular?
Last Updated :
14 Oct, 2024
We’ll walk through how to use ngx-translate
Angular to add multilingual support to your application. You’ll learn how to set up @ngx-translate/core
and @ngx-translate/http-loader
to pull in translation files stored in the assets directory. We’ll cover how to create translation keys, using the translate pipe to display translated content, and implement buttons to switch easily between English and German.
Approach
To implement translation, install @ngx-translate/core and @ngx-translate/http-loader, then create en.json and de.json in the assets/i18n/ directory with translation keys. In app.module.ts, import HttpClientModule, TranslateModule, and TranslateLoader. Set up a TranslateHttpLoader to load files from the assets/i18n/ directory. Use TranslateModule.forRoot() with HttpLoaderFactory to configure it. In the template, use the translate pipe (e.g., {{ 'TITLE' | translate }}) and create buttons to switch between English and German by calling translateService.use('en') or translateService.use('de').
Setting up the Project and installation of Commands
Step 1: Open the terminal and run the following command for running the angular project:
npm install -g @angular/cli
Step 2: Use the below commands to set up the app, and install the required ngx-translate dependencies:
ng new angular-ngx-translate --standalone
cd angular-ngx-translate
npm install @ngx-translate/core @ngx-translate/http-loader
Project Structure:
Project StructureUpdated Dependencies:
"dependencies": {
"@angular/animations": "^18.0.0",
"@angular/common": "^18.0.0",
"@angular/compiler": "^18.0.0",
"@angular/core": "^18.0.0",
"@angular/forms": "^18.0.0",
"@angular/platform-browser": "^18.0.0",
"@angular/platform-browser-dynamic": "^18.0.0",
"@angular/router": "^18.0.0",
"@ngx-translate/core": "^15.0.0",
"@ngx-translate/http-loader": "^8.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
Example: This demonstrates the setting up of translation using @ngx-translate/core and @ngx-translate/http-loader to load English and German locale files and then switching languages via buttons.
CSS
/*de.json*/
{
"TITLE": "Willkommen beim Standalone Component Beispiel",
"DESCRIPTION": "Dies ist ein Beispiel für die Verwendung von ngx-translate mit Angular-Standalone-Komponenten."
}
CSS
/*en.json*/
{
"TITLE": "Welcome to the Standalone Component Example",
"DESCRIPTION": "This is an example of using ngx-translate with Angular standalone components."
}
JavaScript
//src/main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { HttpClient, provideHttpClient } from '@angular/common/http';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { importProvidersFrom } from '@angular/core';
import { AppComponent } from './app/app.component';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './assests/i18n/');
}
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(),
importProvidersFrom(
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
)
]
}).catch((err) => console.error(err));
JavaScript
//src/app/app.component.ts
import { Component } from '@angular/core';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
standalone: true,
template: `
<div class="container">
<h1>{{ 'TITLE' | translate }}</h1>
<p>{{ 'DESCRIPTION' | translate }}</p>
<button (click)="switchLanguage('en')">English</button>
<button (click)="switchLanguage('de')">German</button>
</div>
`,
styles: [`
.container {
padding: 20px;
text-align: center;
}
button {
margin: 5px;
}
`],
imports: [TranslateModule]
})
export class AppComponent {
constructor(private translate: TranslateService) {
// Set the default language
this.translate.setDefaultLang('en');
// Use English as the initial language
this.translate.use('en');
}
switchLanguage(lang: string) {
this.translate.use(lang);
}
}
Run the application:
Start the server using the below command:
ng serve
Output:
Similar Reads
How To Use ngx toastr in Angular17 ?
In Angular, we have a styling component called ngx-toastr, widely used for displaying non-blocking notifications to the user. This component helps enhance the user experience by providing feedback for various actions like success, error, info, and warning messages. By integrating ngx-toastr with Ang
3 min read
How To Use ViewChild in Angular?
In Angular, ViewChild is a powerful decorator that allows you to access and manipulate child components, directives, or DOM elements from a parent component. This feature is essential for scenarios where the parent needs to interact with its child components directly, such as invoking methods, acces
3 min read
How To Use OnChanges In Angular?
Angular is a powerful framework for building dynamic web applications, and one of its core features is the ability to manage and react to changes in component data. One of the key lifecycle hooks in Angular for responding to changes in input properties is the OnChanges lifecycle hook. This hook is h
3 min read
Getting Started with Angular
Angular is a front-end framework for building dynamic web applications. It allows the MVC (Model-View-Controller) architecture and utilizes TypeScript for building applications. So, Angular is an open-source JavaScript framework written in TypeScript. It is maintained by Google, and its primary purp
5 min read
How to use services with HTTP methods in Angular v17?
In Angular 17, services play an important role in managing HTTP requests to backend servers. By encapsulating HTTP logic within services, you can maintain clean, modular, and testable code. In this article, we'll explore how to use services to handle HTTP requests effectively in Angular 17 applicati
3 min read
Language Translator using React
Translator is a web application software tool that facilitate the translation of text from one language to another language using ReactJS. This application allows users to give input Text and select input and output language Format from the list of languages and uses Microsoft Translator API. Users
8 min read
How to Subscribe to an Observable in Angular?
In Angular, managing data streams effectively is important, especially when dealing with asynchronous operations. Observables, a core part of the RxJS library used in Angular, are powerful tools for handling these data streams. In this article, we will explore how to subscribe to Observables in Angu
4 min read
How to iterate over Object in Angular ?
Objects consist of a set of key-value pairs, which are known as Properties. All Properties are named in JavaScript objects and the key part represents the Property name, while the value part represents the property Value. Each element(key-value pair) of the object can be utilized to perform a specif
3 min read
How to use trackBy() Function with ngFor Directive in Angular ?
In this article, we will see How to use the 'trackBy' function with 'ngFor' Directive in Angular, along with understanding their basic implementation through illustrations. The NgFor is used as a structural directive that renders each element for the given collection each element can be displayed on
3 min read
How To Display Values With Interpolation In Angular?
Angular is a powerful framework for building dynamic web applications. One of its key features is data binding, which allows developers to display and update values seamlessly within the UI. Interpolation is a fundamental technique in Angular that enables the integration of component data directly i
3 min read