Internationalization (i18n) in Angular allows you to create multilingual applications. This guide covers the basics of setting up and using i18n in Angular applications.
Setting Up i18n
First, prepare your Angular application for internationalization by installing the necessary dependencies:
ng add @angular/localize
Marking Text for Translation
Mark text in your templates for translation using the i18n attribute:
// app.component.html
Welcome to our application!
Generating Translation Files
Generate translation files using the Angular CLI:
ng extract-i18n --output-path src/locale
This command creates a messages.xlf file in the specified output path.
Translating Text
Translate the text in the generated messages.xlf file:
// messages.xlf
Welcome to our application!Bienvenue dans notre application!
Configuring the Angular App
Configure the Angular application to use the translated files. Update the angular.json file:
This command generates locale-specific build output in the dist folder.
Serving the Application
Serve the application in the specified locale:
ng serve --configuration=fr
Dynamic Locale Switching
To dynamically switch locales at runtime, use the LOCALE_ID and registerLocaleData from Angular's @angular/common package:
// app.module.ts
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
registerLocaleData(localeFr);
@NgModule({
providers: [{ provide: LOCALE_ID, useValue: 'fr' }]
})
export class AppModule { }
Key Points
Internationalization (i18n) in Angular allows you to create multilingual applications.
Install the necessary dependencies using ng add @angular/localize.
Mark text for translation using the i18n attribute.
Generate translation files using the Angular CLI command ng extract-i18n.
Translate text in the generated messages.xlf file.
Configure the Angular application to use the translated files by updating the angular.json file.
Build the application for the specified locale using the ng build --localize command.
Serve the application in the specified locale using the ng serve --configuration=fr command.
Use LOCALE_ID and registerLocaleData to dynamically switch locales at runtime.
Conclusion
Internationalization (i18n) in Angular allows you to create multilingual applications, enhancing the user experience for a global audience. By setting up i18n, marking text for translation, generating translation files, and configuring the application, you can efficiently manage translations in your Angular projects. Happy coding!