Angular i18n Introduction
What is Internationalization?
Internationalization (i18n) is the process of designing and preparing your app to be usable in different languages and regions. The term "i18n" comes from the word "internationalization," where 18 stands for the number of letters between the first "i" and the last "n."
Angular provides built-in tools and libraries that help you internationalize your applications easily, allowing you to reach a wider audience without creating separate codebases for each language.
Why Internationalization Matters
In today's global marketplace, making your application available in multiple languages can significantly increase your user base. Some key benefits include:
- Wider reach: Access users from various countries and regions
- Better user experience: Users feel more comfortable using applications in their native language
- Compliance: Meet legal requirements in certain markets that mandate local language support
- Competitive advantage: Stand out from competitors who don't offer multilingual support
Angular's i18n Approach
Angular offers two main approaches to internationalization:
- The built-in i18n system: Angular's original internationalization system
- Angular Localization package: The newer, more flexible approach using
@angular/localize
In this introduction, we'll focus on understanding the fundamentals that apply to both approaches.
Core i18n Concepts
Before diving into code, let's understand some key concepts:
Locale
A locale is an identifier that refers to a set of user preferences such as language, region, and formatting conventions. Locales are typically represented as language codes (e.g., en
for English) or language-region codes (e.g., en-US
for American English).
Translation
Translation is the process of converting text from one language to another. In Angular, this involves extracting text from your application and replacing it with translations for different locales.
Message Format
Message format refers to how interpolated values (like variables) are handled within translated strings, including pluralization and gender-based text variations.
Setting Up i18n in an Angular Project
Let's walk through the basic steps to set up internationalization in an Angular project:
1. Install Required Packages
If you're using Angular CLI, the necessary i18n tools are already included. For projects using the newer approach, you'll need to install the localize package:
ng add @angular/localize
2. Mark Text for Translation
The first step in internationalizing your application is marking the text that needs translation. Angular provides the i18n
attribute for template elements:
<h1 i18n>Welcome to our application!</h1>
You can also add a description and meaning to provide context for translators:
<h1 i18n="site header|The main header for the application">Welcome to our application!</h1>
For dynamic content, you can use the $localize
tagged template literal:
import { Component } from '@angular/core';
import { $localize } from '@angular/localize/init';
@Component({
selector: 'app-greeting',
template: `<p>{{ greeting }}</p>`
})
export class GreetingComponent {
greeting = $localize`Welcome to our application!`;
}
3. Extract Translation Files
Once you've marked your text for translation, you can extract it into a translation file:
ng extract-i18n --output-path src/locale
This command generates an XML file (usually named messages.xlf
) containing all the marked strings.
4. Create Translated Versions
Next, you need to create copies of the extracted file for each language you want to support:
messages.fr.xlf
for Frenchmessages.es.xlf
for Spanish- etc.
In each file, you'll add the translated text. Here's an example of what the French translation file might look like:
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="welcomeMessage" datatype="html">
<source>Welcome to our application!</source>
<target>Bienvenue dans notre application !</target>
</trans-unit>
</body>
</file>
</xliff>
5. Build for Different Locales
Finally, build your application for each supported locale:
ng build --localize
This creates separate builds for each locale configured in your project.
A Complete Example
Let's put everything together in a simple example of an internationalized Angular component:
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div class="container">
<h1 i18n="@@mainHeader">Welcome to our Multi-Language App!</h1>
<p i18n="@@introText">This application demonstrates Angular's internationalization capabilities.</p>
<div class="user-info">
<p i18n="@@lastLogin">Last login: {{ lastLoginDate | date }}</p>
<p i18n="@@itemCount">You have {{ itemCount }} items in your cart.</p>
</div>
<button i18n="@@checkoutButton">Proceed to Checkout</button>
</div>
`,
})
export class AppComponent {
lastLoginDate = new Date();
itemCount = 5;
}
When built with different locales, this component will display properly translated content to users based on their language settings.
Handling Plurals and Select Forms
Angular i18n also supports plural forms and selections based on values:
Plural Forms
<span i18n>Updated {minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}</span>
This will show:
- "Updated just now" when minutes = 0
- "Updated one minute ago" when minutes = 1
- "Updated X minutes ago" for other values
Select Forms
<span i18n>The author is {gender, select, male {he} female {she} other {they}}</span>
This selects the appropriate pronoun based on the value of the gender variable.
Date, Number, and Currency Formatting
Angular also provides pipes for formatting dates, numbers, and currencies according to the user's locale:
<p>Date: {{ today | date }}</p>
<p>Number: {{ value | number }}</p>
<p>Currency: {{ price | currency }}</p>
When using the localize
option during build, these pipes will automatically format according to the user's locale.
Summary
In this introduction to Angular i18n, we've covered:
- The importance of internationalization for web applications
- Angular's approaches to i18n
- How to mark content for translation
- Extracting and creating translation files
- Building localized versions of your app
- Handling plurals, selections, and formatting
By implementing i18n in your Angular applications, you can reach a wider audience and provide a more personalized experience for users worldwide.
Additional Resources
Exercises
- Create a simple Angular component with text in at least three different HTML elements, and mark them for translation.
- Extract the translation file and create a Spanish version of your translations.
- Build your application with both the original and Spanish locales.
- Add a plural form to your application that handles a counter with different text for zero, one, and multiple items.
- Implement a language switcher that allows users to change the displayed language without refreshing the page (Hint: this requires using the newer
@angular/localize
approach).
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)