NGX-Translate – Switch Multiple Languages with Sample Application in Angular

Internationalization (i18n) and localization (l10n) are important aspects of any modern web application. Internationalization involves adapting an aplication to support multiple languages and locales, while localization involves translating an application’s content and adapting it to a specific language and locale. Angular provides support for i18n and l10n through the @ngx-translate/core library. In this tutorial, we will explore how to handle i18n and l10n in Angular using @ngx-translate/core.

Suppose we have an Angular application that needs to support multple languages and locales. We want to use @ngx-translate/core to handle i18n and l10n in our application. We need to know how to set up the library, load translations, and use translations in our templates and components.

 

How to Add NGX-Translate in Angular 15?

Follow these quick steps to implement the translation feature in Angular:

Step 1 – Install Ngx-Translate
Step 2 – Set up Ngx-Translate
Step 3 – Create translation files
Step 4 – Load translations
Step 5 – Use translations in templates and components

 

Step 1: Install @ngx-translate/core

To use @ngx-translate/core, we need to install it in our Angular application. We can do this using the following command in the terminal:

npm install @ngx-translate/core --save

Step 2: Set up @ngx-translate/core

To use @ngx-translate/core, we need to import it in our app.module.ts file and set up the TranslateModule and TranslateService. We can do this as follows:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';

import { AppComponent } from './app.component';

// Define the translation loader
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In the above code, we define the HttpLoaderFactory function, which creates an instance of the TranslateHttpLoader class. This class is used to load translation files from the server. We then import the HttpClientModule and TranslateModule and set up the translation loader using the TranslateModule.forRoot() method.

 

Step 3: Create translation files

Next, we need to create translation files for our application. These files should be JSON files that contain the translations for each language and locale. We can create a file for each language and locale, and store them in a translations folder in our project. For example, we might have the following files:

- translations/
  - en.json
  - fr.json

The content of en.json might look like this:

{
  "welcome": "Welcome to my app!",
  "greeting": "Hello, {{name}}!",
  "button": "Click me"
}

The content of fr.json might look like this:

{
  "welcome": "Bienvenue sur mon application !",
  "greeting": "Bonjour, {{name}} !",
  "button": "Cliquez ici"
}

Step 4: Load translations

To load translations in our application, we need to use the TranslateService. We can inject the TranslateService in our AppComponent class and use it to load translations from the server. We can also set the default language for our application. We can do this as follows:

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'John Doe';

  constructor(private translate: TranslateService) {
    // Set the default language
    translate.setDefaultLang('en');
    // Load translations for other languages
    translate.use('fr');
  }
}

In the above code, we import the TranslateService and inject it in our AppComponent class. We set the default language to English using the setDefaultLang() method, and then load translations for French using the use() method.

 

Step 5: Use translations in templates and components

Finally, we can use translations in our templates and components using the TranslateService and the translate pipe. We can use the translate pipe to translate text in our templates, like this:

<h1>{{ 'welcome' | translate }}</h1>
<button>{{ 'button' | translate }}</button>

We can also use the TranslateService to translate text in our components, like this:

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-hello',
  template: '<p>{{ greeting }}</p>'
})
export class HelloComponent {
  greeting: string;

  constructor(private translate: TranslateService) {
    // Translate the greeting
    this.translate.get('greeting', { name: 'John Doe' }).subscribe((res: string) => {
      this.greeting = res;
    });
  }
}

In the above code, we import the TranslateService and inject it in our HelloComponent class. We use the translate.get() method to translate the greeting text, and pass in an object that contains the name variable, which is used in the translation.

 

Some Common Problems with Possible Solutions:

Here are some common questions, problems, and features that developers may face when using @ngx-translate/core in Angular:

 

 

How do I change the default language of my application?

To change the default language of your application, you can use the setDefaultLang() method of the TranslateService. For example, to set the default language to French:

this.translate.setDefaultLang('fr');

How do I load translations asynchronously?

To load translations asynchronously, you can use the TranslateHttpLoader class and the HttpClientModule module. First, create a new function that returns a new TranslateHttpLoader instance, like this:

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

Then, import the HttpClientModule module in your AppModule and set up the TranslateModule like this:

TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useFactory: HttpLoaderFactory,
    deps: [HttpClient]
  }
})

How do I use a custom translation loader?

To use a custom translation loader, you can create a new class that implements the TranslateLoader interface. For example:

import { TranslateLoader } from '@ngx-translate/core';
import { Observable, of } from 'rxjs';

export class CustomLoader implements TranslateLoader {
  getTranslation(lang: string): Observable<any> {
    // Implement your custom translation loading logic here
    return of({ hello: 'Bonjour' });
  }
}

Then, set up the TranslateModule like this:

TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useClass: CustomLoader
  }
})

How do I use placeholders in translations?

To use placeholders in translations, you can use the {{variable}} syntax. For example:

{
  "greeting": "Hello, {{name}}!"
}

Then, in your component or template, you can use the translate.get() method to translate the string and pass in the variables:

this.translate.get('greeting', { name: 'John' }).subscribe((res: string) => {
  console.log(res); // "Hello, John!"
});

How do I translate dynamically added content?

To translate dynamically added content, you can use the translate.instant() method to translate the string synchronously. For example:

const element = document.createElement('div');
element.innerText = this.translate.instant('hello');

How do I use a fallback language?

To use a fallback language, you can set the fallbackLang property of the TranslateService. For example, to use English as the fallback language:

this.translate.setDefaultLang('en');
this.translate.use('fr');
this.translate.setFallbackLang('en');

How do I change the language at runtime?

To change the language at runtime, you can use the translate.use() method. For example:

this.translate.use('fr');

How do I use a pipe to translate content?

To use a pipe to translate content, you can use the translate pipe in your template. For example:

<h1>{{ 'greeting' | translate:{ name: 'John' } }}</h1>

How do I handle missing translations?

To handle missing translations, you can set the missingTranslationHandler property of the TranslateService. For example:

this.translate.missingTranslationHandler = {
  handle: (keymessage: string, params: any) => {
     console.warn(Missing translation for '${key}');
     return key;
    }
};

This handler will log a warning message to the console and return the translation key if a translation is missing.

 

How do I translate pluralized strings?

To translate pluralized strings, you can use the `translate.get()` method with a pluralization key. For example:

{
  "apples": {
    "zero": "No apples",
    "one": "One apple",
    "other": "{{count}} apples"
  }
}

Then, in your component or template, you can use the translate.get() method to translate the pluralized string and pass in the count:

this.translate.get('apples', { count: 0 }).subscribe((res: string) => {
  console.log(res); // "No apples"
});

this.translate.get('apples', { count: 1 }).subscribe((res: string) => {
  console.log(res); // "One apple"
});

this.translate.get('apples', { count: 5 }).subscribe((res: string) => {
  console.log(res); // "5 apples"
});

How do I use namespaces to organize translations?

To use namespaces to organize translations, you can set the defaultNamespace property of the TranslateModule and use the ns attribute in your translations. For example:

TranslateModule.forRoot({
  defaultNamespace: 'app',
  loader: {
    provide: TranslateLoader,
    useFactory: HttpLoaderFactory,
    deps: [HttpClient]
  }
})
{
  "app:greeting": "Hello",
  "app:goodbye": "Goodbye"
}

Then, in your component or template, you can use the translate.get() method with the namespace:

this.translate.get('greeting', { }, 'app').subscribe((res: string) => {
  console.log(res); // "Hello"
});

Conclusion

In this tutorial, we have learned how to implement internationalization and localization in an Angular application using @ngx-translate/core. We walked through the process of setting up the library, loading translations, and using the translate pipe and service in our templates and components.

Additionally, we covered several common questions and problems that developers may face when using @ngx-translate/core, such as how to handle pluralization, fallback translations, and namespaces. By understanding these features and how to use them effectively, developers can create applications that are accessible and user-friendly for people from all over the world.

Leave a Comment

Your email address will not be published. Required fields are marked *