Angular Localization with Ivy
Tags: angular, webdev, javascript, programming
Published: 2023-01-30 06:06:53

Part of the new Angular rendering engine, Ivy having a new method for localizing applications- especially extracting and translating text. This blog explains the benefits and some of the implementation of this new technique.

## Localization with Ivy

Earlier to Ivy, the only way to add localizable messages to an Angular app was to mark them in component templates using the i18n attribute

```
<code><div i18n="">Welcome to Angular Localization with Ivy Blog</div>
</code>

```

The Angular compiler would change this text when compiling the template with different text if a set of translations was given in the configuration of the compiler. The i18n tags are very strong. They can be used in attributes and also as content. They can have complex nested ICU (International Components for Unicode) expressions. They can have extra information attached to them.

The most important trouble was that translation supposed to happen throughout template compilation, which occurs right at the start of the build pipeline. The result of this is that full build, compilation, bundling, minification, etc. Had to happen for every locale that you assumed to support in your app.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n30x6c2u39tuygad4npu.png)
(Build Time will vary depending on project size)


While a single build took 2 minutes, then the total build time to support 4 locales would be 2 mins x 4 locales = 8 mins.

Furthermore, it was not possible to mark text in the translation application, only text in component templates, this resulted in difficult workarounds where artificial components were created fully to hold text that would be translated.

Ultimately, it was not possible to load transactions at runtime, which intend applications couldn't be provided to an end-user who want to allow translations of their own, without building the app themselves.

The new localization approach or technique is fixed around the concept of marking strings in code with a template exact tag handler called $localize. The thought is that strings that require to be translated are “marked” using the following tag:

```

<code>const txtMessage = $localize `Welcome to Angular Localization with Ivy Blog`;</code>

```

This $localize keyword can be a real function that can do the translation at runtime, in the browser. But substantially, it is also a global identifier that survives minification. This means it can behave normally as a marker in the code that a static post-processing tool can use to change the original text with translated text before the code is deployed. Like the following example code:

```

<code>warning = $localize `${this.process} is not correct`;</code>

```

Could change with

```

<code>warning = "" + this.process + ", ce n'est pas bon.";</code>

```

The outcome is that all references to $localize are removed, and there is zero runtime cost to rendering the translated text.

The Angular template compiler, for Ivy, has been restructured to generate $localize tagged strings instead of doing the translation ourselves. For example, the following template:

```

<code><h1 i18n="">Welcome to Angular Localization with Ivy Blog</h1>
</code>

```

May be compiler can do similar to the following syntax:

```

<code>
??elementStart(0, &quot;h1&quot;);                //<h1>
??i18n(1, $localize`Welcome to Angular Localization with Ivy Blog`);    //  Welcome to Angular Localization with Ivy Blog
??elementEnd();                         //</h1>
</code>

```

That means once the compiler has completed its work all the template text marked with i18n attributes have been transformed to $localize marked strings which can be processed much like any other marked string.

### Read More: [Migrating And Configuring Eslint In Angular 11](https://www.ifourtechnolab.com/blog/migrating-and-configuring-eslint-in-angular-11)

Also note that the $localize tagged strings can occur in any code and are not affected by minification, so when the post preprocessing tool might receive code that looks like the following:

```

<code>...var El,kl=n("Hfs6"),Sl=n.n(kl);El=$localize`Welcome to Angular Localization with Ivy Blog`;let Cl=(()=>{class e{constructor(e)...</code>

```

It is quite able to identify and translated the tagged message. The result is that we reorder the build pipeline to do translation at the very end of the process, resulting in a significant build time improvement.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5qhlya25ptzj4bwyou8h.png)
(Build Time will vary depending on project size)

Here you can see that the build time is still 2 minutes, but since the translation is done as a post processing step, we only obtain that build cost one time. Also, the post processing of the translation is very quick due to the tool only has to parse the code for $localize marked strings. In this case near 5 seconds.

The outcome is that the total build time for 4 locales is now 2 minutes + (4 x s seconds) = 2 Minutes 20 seconds. In comparison to 8 minutes for the pre-Ivy translated builds.

The post-processing of translations is already built into the Angular CLI and in case, you have configured your projects based on our i18n guide you should already be benefitting from these faster build times.

Presently the use of $localize in application code is note moreover publicly supported or documented. It needs a new message extraction tooling. The present (pre-Ivy) message extractor does not find $localize text in the application code. This is existence integrated into the CLI now and should be released as part of 10.1.0.

We are also looking at how we can improve best support translation in 3rd party libraries using the new techniques or approach. Since this would affect the Angular Package Format we hope to run a Request for Comment before implementing that.

Meanwhile, enjoy the improved build times and keep an eye out for full support of application-level localization of text.

## How to Implement Localization in Angular 10?

I18n or Internationalization is the process of designing and developing your app for various locales around the world. Localization is the process of building versions of your app for various locales, adding extracting text for translation into several languages, and formatting dates for specific locales.

A locale recognizes a region in which people speak a specific language. The locale identifies the formatting and parsing of times,dates,currencies and numbers along with measurement units and the time zones translated names, languages, and countries.

To implement your app for translations you should have a basic understanding of the Template, Components, Angular CLI, and XML.

## Steps to Localize Your Angular App

Create a new project using an Angular CLI

```

<code>ng new i18nDemo</code>  

```

For localization our demo, modify the app.component.html like the following code:

```
<code><pre><code><h1> Localization Demo in Angular using i18n</h1>
<h3 i18n="@@myName"> Hello, My name is Girish</h3>
<p>This text will remain same in all languages</p>
<hr>
<ng-container>
<a href="/{{language.code}}/">
</a><button class="button">{{language.label}}</button><a href="/{{language.code}}/">
</a>
</ng-container>
</code>
                </pre>

<p>Modify the app.component.ts file like the following code:</p>

<div class="bl-customimg pdmtop10">
<center><img alt="hindi1" class="img-fluid" height="261" src="https://www.ifourtechnolab.com/pics/hindi-code1.webp" title="hindi1" width="575"></center>
</div>

<p>Add the localize package @angular/localize using Angular CLI by running the following command:</p>
<br>
<pre><code>ng add @angular/localize</code>
                  </pre>

<p>This command modifies your project’s package.json and jolyfills.ts files to import the @anuglar/localize package</p>

<p>Then create a translation file using Angular CLI by running the following command:</p>
<br>
<pre><code>ng xi18n</code> 
                  </pre>

<p>This will create the messages.xlf translation file whose code is shown below:</p>
<br>
<pre><code>
<!--?xml encoding="UTF-8" version="1.0"-->
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file datatype="plaintext" original="ng2.template" source-language="en-US"><p>
<trans-unit datatype="html" id="cd299a9a7bd5d4962e27040b729b21cb4eb7807a">
<source> Localization Demo in Angular using i18n
<context-group purpose="location">
<context context-type="sourcefile">src/app/app.component.html</context>
<context context-type="linenumber">1</context>
</context-group>
</trans-unit>
<trans-unit datatype="html" id="myName">
<source> Hello, My name is Girish
<context-group purpose="location">
<context context-type="sourcefile">src/app/app.component.html</context>
<context context-type="linenumber">2</context>
</context-group>
</trans-unit></p>
</file>
</xliff>
<!--?xml--></code>
                  </pre>

<p>We shall use the Google Translate for Translation, Now create Spanish messages.es.xlf translation file which is having a code shown below.</p>

<pre><code>
<!--?xml encoding="UTF-8" version="1.0"-->
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file datatype="plaintext" original="ng2.template" source-language="en-US">
<trans-unit datatype="html" id="cd299a9a7bd5d4962e27040b729b21cb4eb7807a">
<source> Localization Demo in Angular using i18n
<target>Demostraci&oacute;n de localizaci&oacute;n en angular usando i18n</target>
<context-group purpose="location">
<context context-type="sourcefile">src/app/app.component.html</context>
<context context-type="linenumber">1</context>
</context-group>
</trans-unit>
<trans-unit datatype="html" id="myName">
<source> Hello, My name is Girish
<target>Hola</target>
<context-group purpose="location">
<context context-type="sourcefile">src/app/app.component.html</context>
<context context-type="linenumber">2</context>
</context-group>
</trans-unit>
</file>
</xliff>
<!--?xml--></code>
                  </pre>
</code>

```

### Looking to [Hire Angular Developer](https://www.ifourtechnolab.com/hire-angular-js-developer)? Your Search ends here.

Then we will create Hindi messages.hi.xlf file for translation which will have code shown below.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ga73z7e7h9vp5tx5388.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m6b9n0pm1lpi0syhgr6z.png)
(Home Page Looks Like this)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1e9pyieosqrnib9k7diq.png)
(When we click on Hindi then the page will look like this)



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/njbn6gqvya1upd3335yb.png)
(When we click on Spanish then the page will look like this)

### Conclusion

In this blog, we have discussed the Angular rendering engine, Ivy, and add a new approach to localizing applications. We have also explained the advantages and few of the demo for its implementation.