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 truncate text in Angular2?
Approach: It is easy to truncate text in Angular. The truncated text helps us to remove or cut-off portions of text. It abruptly ends the text, reducing the length of the text. It removes text in accordance with the truncate function used. Syntax: String length is greater than the given characters.
2 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 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
How To Translate Text From an Image Using Google Translate
Are you finding it tough to translate text from pictures? Now, you do not need to worry anymore because Google now lets users translate text from images effortlessly. If you're overseas and want to read important signs, flyers, and posters, the Google Image Translation feature will help you. With a
3 min read
How to Translate a Web Page in Another Language?
With the internet connecting people globally, encountering websites in languages you don't understand is increasingly common. That's why most web browsers offer built-in translation features to help you easily translate web pages. Web browsers use translation services to convert text on web pages to
3 min read
How to use Pipes within ngModel on input Element in Angular ?
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. In this article, we will learn about Usin
3 min read
How to truncate the text using Angular Pipe and Slice ?
Angular Pipe and Slice can be used to manipulate or transform the data in a specific format. Angular Pipes can be utilized to format or transform data directly before displaying it in the Angular template. The Slice is a built-in method in JavaScript that enables the users to extract a part of the a
3 min read