@angular/localize
package or by using libraries like ngx-translate
. Below, I'll provide an example using ngx-translate
Step-by-Step Guide to Integrate ngx-translate
Install Dependencies:
First, install the necessary packages:
bashnpm install @ngx-translate/core @ngx-translate/http-loader --save
Set Up the Translation Module:
In your
app.module.ts
, configure the translation module:typescriimport { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule, HttpClient } from '@angular/common/http'; import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { AppComponent } from './app.component'; // Function to create a new TranslateHttpLoader export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http); } @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, HttpClientModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient], }, }), ], bootstrap: [AppComponent], }) export class AppModule {}
Create Translation Files:
Create a folder named
assets/i18n
and add your translation JSON files. For example:en.json
(English)json{ "HELLO": "Hello", "WELCOME": "Welcome to our application" }
fr.json
(French)js{ "HELLO": "Bonjour", "WELCOME": "Bienvenue dans notre application" }
Use Translations in Components:
In your component, inject the
TranslateService
and use it to get translations:typescriptimport { Component } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'app-root', template: ` <h1>{{ 'HELLO' | translate }}</h1> <p>{{ 'WELCOME' | translate }}</p> <button (click)="switchLanguage('en')">English</button> <button (click)="switchLanguage('fr')">Français</button> `, }) export class AppComponent { constructor(private translate: TranslateService) { translate.setDefaultLang('en'); translate.use('en'); // Set the initial language } switchLanguage(language: string) { this.translate.use(language); } }
Serve Your Application:
Now, run your application:
basng serve
You should see the text displayed in English, and clicking the buttons will switch the language to French.
Conclusion
This setup allows you to easily add more languages by creating additional JSON files in the assets/i18n
directory. Just follow the same format for each new language, and your application will support multiple languages seamlessly.