Internationalization (i18n) is the process of designing and preparing your Angular application to be adaptable to different languages and regions without requiring engineering changes to the source code. This is crucial for applications that aim to reach a global audience.

Key Concepts

  1. Localization (l10n): Adapting your application to a specific locale, including translating text, formatting dates and numbers, and handling other locale-specific data.
  2. Locale: A set of parameters that defines the user's language, country, and any special variant preferences.
  3. Translation Files: Files that contain the translated text for different locales.

Steps to Implement Internationalization in Angular

  1. Setting Up Angular i18n

Angular provides built-in support for internationalization through the @angular/localize package. To set it up:

  1. Install the package:

    ng add @angular/localize
    
  2. Mark Text for Translation: Use the i18n attribute to mark text for translation in your templates.

    <h1 i18n="@@welcomeMessage">Welcome to our application!</h1>
    

  1. Extracting Translation Files

  1. Extract Messages: Use Angular CLI to extract the messages into an XLIFF file.

    ng extract-i18n
    

    This command generates a messages.xlf file in the src/locale directory.

  2. Translate Messages: Create copies of the messages.xlf file for each locale and translate the text.

    <trans-unit id="welcomeMessage" datatype="html">
      <source>Welcome to our application!</source>
      <target>Bienvenido a nuestra aplicación!</target>
    </trans-unit>
    

  1. Configuring the Application for Multiple Locales

  1. Update angular.json: Add configurations for each locale in the angular.json file.

    "projects": {
      "your-app": {
        "i18n": {
          "sourceLocale": "en",
          "locales": {
            "es": "src/locale/messages.es.xlf"
          }
        }
      }
    }
    
  2. Build for Different Locales: Build the application for each locale.

    ng build --localize
    

  1. Serving the Application

  1. Serve the Application: Use a web server to serve the localized versions of your application. Each locale will have its own directory under the dist folder.

  1. Dynamic Locale Switching

To dynamically switch locales in your application, you can use Angular's LOCALE_ID and registerLocaleData functions.

  1. Import Locale Data:

    import { registerLocaleData } from '@angular/common';
    import localeEs from '@angular/common/locales/es';
    
    registerLocaleData(localeEs);
    
  2. Provide Locale ID:

    import { LOCALE_ID } from '@angular/core';
    
    @NgModule({
      providers: [
        { provide: LOCALE_ID, useValue: 'es' }
      ]
    })
    export class AppModule { }
    

Practical Example

Example Component

<!-- app.component.html -->
<h1 i18n="@@welcomeMessage">Welcome to our application!</h1>
<button (click)="switchLocale('es')">Switch to Spanish</button>
<button (click)="switchLocale('en')">Switch to English</button>

Example Component Logic

// app.component.ts
import { Component } from '@angular/core';
import { LOCALE_ID, Inject } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(@Inject(LOCALE_ID) private localeId: string) {}

  switchLocale(locale: string) {
    // Logic to switch locale
    // This might involve reloading the application with the new locale
    window.location.href = `/${locale}/`;
  }
}

Exercises

Exercise 1: Mark Text for Translation

  1. Mark the following text for translation in your Angular template:
    <p>Thank you for using our service!</p>
    

Solution:

<p i18n="@@thankYouMessage">Thank you for using our service!</p>

Exercise 2: Extract and Translate Messages

  1. Extract the messages and translate the thankYouMessage to Spanish.

Solution:

  • Extract messages:
    ng extract-i18n
    
  • Translate in messages.es.xlf:
    <trans-unit id="thankYouMessage" datatype="html">
      <source>Thank you for using our service!</source>
      <target>¡Gracias por usar nuestro servicio!</target>
    </trans-unit>
    

Exercise 3: Configure and Build for Locales

  1. Add the Spanish locale to angular.json and build the application.

Solution:

  • Update angular.json:
    "projects": {
      "your-app": {
        "i18n": {
          "sourceLocale": "en",
          "locales": {
            "es": "src/locale/messages.es.xlf"
          }
        }
      }
    }
    
  • Build the application:
    ng build --localize
    

Conclusion

Internationalization is a powerful feature in Angular that allows you to create applications that can be easily adapted to different languages and regions. By following the steps outlined in this section, you can ensure that your application is ready to reach a global audience. In the next topic, we will explore Angular Animations and how to add dynamic effects to your application.

© Copyright 2024. All rights reserved