DEV Community

Cover image for How to Implement Angular Localization
George Kasiouras
George Kasiouras

Posted on

How to Implement Angular Localization

Angular localization can be a challenging task, from internationalization to content extraction all the way back to deployment. This is what you'd typically do with Angular i18 and other alternatives, due to their limitations.

But there is a way to bypass these limitations. If you are looking to nail the localization of your Angular application, we have got you covered with this step-by-step guide to easily localize your app with an Angular i18 alternative called Transifex Native. 

Angular i18 Limitations

If you've ever worked on localizing an Angular app, you most likely already know that the most popular way to localize your Angular app is through the built-in Angular i18 module. But this process has some limitations:

The locale cannot be changed at once but all the languages must be compiled and generated individually
Custom translation loaders are not easy to create
It only supports XML files which are more difficult to maintain than some alternatives.

There are some other libraries, i18next for instance, that can bypass these limitations, but all of these methods require you to extract strings and deploy them when they are translated—which demands more effort to execute different localization tasks like branching, content splitting, or releasing.

Angular localization can be simplified using a different approach—Transifex Native—where you can directly use your code without managing files. All translatable content is managed by the platform and comes with added functionality that you can control. To use Transifex Native for localizing your application, simply sign up to the platform and get started with your project.

3 Benefits Over Angular i18

We have discussed the limitations of the file-based approach for your app localization earlier in the article. But before diving into our recommended alternative, here are 3 ways the Transifex Native can solve the existing drawbacks.

  1. Automate file management: The biggest drawback is transferring files to and from the TMS to your platform. This process gets even more complex when the number of files increases and hinders scalability. An easy solution to manual file management is automation which can be achieved with Transifex Native.

  2. Easier for developers: Developers can focus more on the code than the localization process itself as TX Native integrates localization within the code.

  3. Better results: No manual errors or updating translations to your app. Native also optimizes the entire process by giving different team members the scope to completely focus on their roles without worrying about coordinating everything on their platform.

Now that you understand how Transifex Native can simplify your localization process, let’s take you through a step-by-step guide on how you can localize your Angular app.

How To Localize Angular Application?

To localize your app using Transifex, simply add the Native SDK and you are ready to serve translations over the air.

Once you have created your project, follow the next steps to install the Transifex SDK in your application and get started with your Angular localization:

Generate Native Credentials

In all data exchanges between the Native and your application, the Native credentials --TOKEN and SECRET -- are used.

API TOKEN – Reads (GET) content from Transifex Native to your application
API SECRET – Sends (POST) content from your application to Transifex Native
Click on “Generate Native Credentials” and choose the TX Native SDK as Angular. It’s essential to copy and save the SECRET key for the future, as it cannot be recovered.

Installation

To get started, you need to install the JavaScript SDK and add the additional Angular Components library to your code. Install the library and its dependencies using:

npm install @transifex/native @transifex/angular --save
Enter fullscreen mode Exit fullscreen mode

Declaration & Initialization Of The TX Native

It is necessary to initialize the TX Native library at two locations in the angular bootstrap process to use its objects globally:

  • NgModule Initialization- To access all the elements provided by the TX Native Angular SDK in our application, you need to add the Native module to the code as follows:
@NgModule({
 declarations: [
  AppComponent,
  LoginComponent,
  TermsComponent,
  HomeComponent,
  PrivacyComponent
 ],
 imports: [
  AppRoutingModule,
  BrowserModule,

  //TX Native module declaration
  TXNativeModule.forRoot(),
 ],
 providers: [,
 ],
 bootstrap: [AppComponent]
}]
Enter fullscreen mode Exit fullscreen mode
  • Application Bootstrap- Insert the translation service provided by the SDK and initialize the library using the token generated by Transifex. The service is a singleton object that can be used in any part of the application—an advantage of initializing the native library globally.

To implement this, use the following code:

import { Component } from '@angular/core';
import { TranslationService } from '@transifex/angular';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['.app.component.scss']
})
export class AppComponent {
 constructor(private translationService: TranslationService) {
  // TX Native library initialization
  translationService.init({
   token: '---- insert your TX Native token here -----',
  });
 }
 async ngOnInit()
  await this.translationService.getLanguages();
  await this.translationService.setCurrentLocale('el');
 }
}
Enter fullscreen mode Exit fullscreen mode

Internationalize Your Code With TX Native

Once the SDK is installed, it’s time to mark the content for translation. Transifex Native provides multiple components that can be used in your code for internationalizing your content.

1. T Component
This is used to mark the strings for translation, as in the example given below.

<p>
  <label>
   <T str="Password" key="label.password"></T>
  </label>
  <input type="password" name="password" />
</p>
Enter fullscreen mode Exit fullscreen mode

Safe render of the HTML result after translation is possible with the T component, using the parameter sanitize. Ensure that the str (Source String) property on the T component is always a valid ICU message format template. In the case it is nested within a tx-instance tag, the T component will use new instances to fetch translations.

2. UT Component

A UT component has similar behavior to a T component, but when the inline property is true, it renders the source string as HTML inside a div tag or a span tag.

Inline property can be described as:

Prop -- Type -- Description
inline - Boolean - If should wrap the translation with span (true) of with a div (default, if false)

3. The @T Decorator
This component is used in variable declarations inside classes and components to have properties with the translation and use them in templates and code.

Decorators can use an alternative instance instead of the main TX Native one by passing them an instance configuration.

4. The Translate Pipe
This can be used in templates for inline string translations. However, one limitation that the translate pipe has is that it cannot translate strings with embedded HTML.

In the case it is nested within a tx-instance tag, the translate pipe will use new instances to fetch translations.

These components are used to execute the primary internationalization process like marking the strings for translation or passing attributes. If you want to get some variables translated in the component’s code, you can implement it as follows:

@component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['.app.component.css']
})
export class AppComponent {
 @T( 'Angular Transifex Native Demo')
 mainTitle!: string;
...
Enter fullscreen mode Exit fullscreen mode

And then use the variable in the component’s template like this:

<span><UT str='{title} is running!" [vars]="{ title: mainTitle }"></UT></span>
Enter fullscreen mode Exit fullscreen mode

Using The Translation Service

To initialize the TX Native object, this is the main service exposed by the SDK. As the translation service is a singleton instance, the initialization will be shared across the entire application—inside your libraries, components, or the code.

Additionally, it keeps a collection of TX Native instances that can be added to the default instance for particular purposes.
Each additional instance should have the following configuration:

ITXInstanceConfiguration {
 token: string;
 alias: string;
 controlled: boolean;
}
Enter fullscreen mode Exit fullscreen mode

To add and retrieve the additional instances, exposed methods addInstance and getInstance are used, respectively.

You can utilize the translation service to:

  • Add or delete an alternative instance

  • Initialization of an instance

  • Set or get the current locale

  • Translation of a string

The translation service also allows retrieving translations that match a given list of tags—to fetch groups of translations in batches—for lazy loading and performance. To do this, you can use the fetchTranslations method.

The Language Picker Component

For easy localization, the Angular SDK includes a ready-to-use component called a language picker. This component switches the application’s selected language when the current locale is changed. The language picker uses the Translation Service internally.

The component accepts this property:

  • className: The CSS class that is applied to the tag
    And it returns this property:

  • localeChanged: Handles the change of locale

Using the language picker component looks like this:

<tx-language-picker
 className="placeBottomLeft"
 (localeChanged)="onLocaleChanged($event)"></tx-language-picker>
Enter fullscreen mode Exit fullscreen mode

You always can implement a language picker of your choice using the Translation Service and different methods provided by the Native.

Pushing Source Content For Localization

After you have marked the strings in the code for translation, you can push them to TX Native. To do so, you can:

  • Use a CLI tool that scans the code and extracts strings wrapped using the Native SDK. It scans all files in the selected folder and pushes the marked content to your Native project

  • Use the SDK itself programmatically to push arbitrary strings coming from different sources like databases or custom files.

Find all the details to push your source strings to Transifex in this documentation.

Preview Translations

Transifex Native automatically displays translated content in your application—simply add a language picker in your code. Transifex comes with an in-built language picker to request translations, but you can build your own picker using Native JS API and add the related logic.

The translations are fetched from the CDS to the cache and made available when a new language is selected.

To help you understand, here’s an example:

tx.setCurrentLocale('el)
 .then(() => console.log('content loaded'))
 .catch(console.log);
Enter fullscreen mode Exit fullscreen mode

Fetching Translations

Once you have pushed the translatable content, you can view or edit it in the Transifex editor. There is also a list of tools to assist you in your localization processes.

Every time you save a translation, it automatically becomes available over the air in your application. Transifex Native translations are served from a secure CDN server, called Transifex CDS, and are updated once per hour. You do not need to restart your server or deploy any code to see the newest translations.

Optimizing The App Localization Process

Apart from simplifying the localization process as a whole, Transifex Native is loaded with a wide range of tools that can optimize your workflow further.

Using String Keys

Keys are unique identifiers that can be reused in other parts of the code to minimize the amount of content your localization team has to translate. Multiple strings with the same key are pushed as a single string in TX Native—which means your team now needs to add only a single translation.

Keys can be used by adding the _key parameter to the T component and marking strings as translatable in the Native function.

Content Splitting

Segment your string content using tags and optimize the bundle size of downloaded translations over the air. This is useful when you have a large content resource but not all parts of your app need the whole content. To segment your content, simply use any preexisting tags or create a new one.

This can also be used to segment content across feature branches—tag the strings, localize them, test them, and deploy them.

For example:

$ git checkout -b new-login-page
$ txjs-cli push srv/ --append-tags="new-login-page"
Enter fullscreen mode Exit fullscreen mode

Automated Releasing

When your feature or branch is ready for deployment, clean up all the faulty content from the Native CLI tool using the purge attribute when pushing. This makes the entire process automated and you don’t end up with multiple string history.

Purge will parse all code files found in the and keep only those phrases detected there, removing any other phrases.

Conclusion

Solutions such as Angular i18 require your team to go back and forth with content to be localized. Transifex Native bypasses the need for manual file management and provides a simpler way to localize your app.

Top comments (0)