Localization In Angular With i18n

Introduction

 
In this article, we will learn how to make our Angular app available in different languages using i18n and localization. We will create an Angular application and configure it to serve the content in three different languages. We will also deploy our app to Google Firebase and see how localization works in real-time.
 
We will use Angular 7 and VS Code to develop our application. Take a look at the application output.
 
Localization In Angular With i18n 

Source Code

 
Get the source code for this application from GitHub.
 

What is i18n?

 
i18n, also known as internationalization, is the process of making our app support various languages to extend the reach to a worldwide audience.
 

What is Localization?

 
Localization is the process for translating the app to a particular language. We need to apply internationalization to the application and after that we can localize it. Localization allows us to serve our application in different languages.
 

Creating an Angular 7 app

 
The first step is to create an Angular 7 app. If you are new to Angular, I would suggest you read my article Getting Started With Angular 7.0 to learn how to set up Angular development environment in your machine.
 
Run the following command to create the app.
  1. ng new i18nDemo  
Open the i18nDemo app using VS code.
 

Setting up the app component

 
Open app.component.html file. Replace the already existing text with the following code.
  1. <h1 i18n>  
  2.   Localization Demo in Angular using i18n  
  3. </h1>  
  4.   
  5. <h3 i18n="@@myName">  
  6.   Hello, My name is Ankit  
  7. </h3>  
  8. <p>This text will remain same in all languages</p>  
  9. <hr />  
You can observe that we have marked <h1> and <h3> tags with i18n attribute. This is a way to tell Angular to consider this text as translatable content. We will explore i18n attribute in detail in the next section.
 

Creating a translation source file

 
Run the following command in the CLI to create a translation source file.
  1. ng xi18n --output-path translate  
It will create a folder called translate and create a messages.xlf file inside it. Open the file and you can observe the following XML code inside it.
  1. <?xml version="1.0" encoding="UTF-8" ?>    
  2. <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">    
  3.   <file source-language="en" datatype="plaintext" original="ng2.template">    
  4.     <body>    
  5.       <trans-unit id="3f2feb6d5fb690628177afa3ade2519db69ba838" datatype="html">    
  6.         <source>Localization Demo in Angular using i18n</source>    
  7.         <context-group purpose="location">    
  8.           <context context-type="sourcefile">app/app.component.html</context>    
  9.           <context context-type="linenumber">1</context>    
  10.         </context-group>    
  11.       </trans-unit>    
  12.       <trans-unit id="myName" datatype="html">    
  13.         <source>Hello, My name is Ankit</source>    
  14.         <context-group purpose="location">    
  15.           <context context-type="sourcefile">app/app.component.html</context>    
  16.           <context context-type="linenumber">5</context>    
  17.         </context-group>    
  18.       </trans-unit>    
  19.     </body>    
  20.   </file>    
  21. </xliff>   
This file contains a list of <trans-unit> tags. These tags will have all the content that was marked for translation using i18n attribute. You can also observe that each <trans-unit> tags has an id property associated with it. This unique id will be generated by default for each tag that was marked with i18n attribute. We can also customize the id by providing a name prefixed with "@@" as we have done with <h3> tag in previous section. Hence, the id for <h3> tag is “myName” as we defined it. There is no entry for the <p> tag in translation file because we have not marked it with i18n attribute. Angular translation tool will not consider it for translations.
 
If you change the text for any tag in your HTML file, you need to regenerate the translation file. Regenerating the file will override the default id of <trans-unit> tags. Hence, it is advisable to provide custom ids to each translatable tag to maintain consistency.
 
Hence, we have successfully implemented i18n to our app. In the next section, we will extend it to make it available to different languages.
 

Translating the content

 
We will translate our application into two new languages apart from English, which are Spanish and Hindi. Make three copies of the messages.xlf file and rename them to messages.en.xlf, messages.es.xlf and messages.hi.xlf. These file names can be customized as per your choice but the extension should be .xlf.
 
Open messages.es.xlf and put in the following content in it.
  1. <?xml version="1.0" encoding="UTF-8" ?>    
  2. <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">    
  3.   <file source-language="en" datatype="plaintext" original="ng2.template">    
  4.     <body>    
  5.       <trans-unit id="3f2feb6d5fb690628177afa3ade2519db69ba838" datatype="html">    
  6.         <source>Localization Demo in Angular using i18n</source>    
  7.         <target>Demostración de localización en angular usando i18n</target>    
  8.         <context-group purpose="location">    
  9.           <context context-type="sourcefile">app/app.component.html</context>    
  10.           <context context-type="linenumber">1</context>    
  11.         </context-group>    
  12.       </trans-unit>    
  13.       <trans-unit id="myName" datatype="html">    
  14.         <source>Hello, My name is Ankit</source>    
  15.         <target>Hola, mi nombre es Ankit</target>    
  16.         <context-group purpose="location">    
  17.           <context context-type="sourcefile">app/app.component.html</context>    
  18.           <context context-type="linenumber">5</context>    
  19.         </context-group>    
  20.       </trans-unit>    
  21.     </body>    
  22.   </file>    
  23. </xliff>
This is the same content as the original messages.xlf file, but we have added a <target> tag corresponding to each <source> tag. The <target> tag contains the translated text for the content inside the <source> tag. Here I am using Google translate for the translation but in real time applications, a language expert will translate the contents from messages.xlf file.
 
Similarly open the messages.hi.xlf and put in the following content in it.
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">  
  3.   <file source-language="en" datatype="plaintext" original="ng2.template">  
  4.     <body>  
  5.       <trans-unit id="3f2feb6d5fb690628177afa3ade2519db69ba838" datatype="html">  
  6.         <source>Localization Demo in Angular using i18n</source>  
  7.         <target>I18n का उपयोग कर कोणीय में स्थानीयकरण डेमो</target>  
  8.         <context-group purpose="location">  
  9.           <context context-type="sourcefile">app/app.component.html</context>  
  10.           <context context-type="linenumber">1</context>  
  11.         </context-group>  
  12.       </trans-unit>  
  13.       <trans-unit id="myName" datatype="html">  
  14.         <source>Hello, My name is Ankit</source>  
  15.         <target>हेलो, मेरा नाम अंकित है</target>  
  16.         <context-group purpose="location">  
  17.           <context context-type="sourcefile">app/app.component.html</context>  
  18.           <context context-type="linenumber">5</context>  
  19.         </context-group>  
  20.       </trans-unit>  
  21.     </body>  
  22.   </file>  
  23. </xliff>  
Finally, we will make English translation file. Open messages.en.xlf and put in the following content in it.
  1. <?xml version="1.0" encoding="UTF-8" ?>    
  2. <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">    
  3.   <file source-language="en" datatype="plaintext" original="ng2.template">    
  4.     <body>    
  5.       <trans-unit id="3f2feb6d5fb690628177afa3ade2519db69ba838" datatype="html">    
  6.         <source>Localization Demo in Angular using i18n</source>    
  7.         <target>Localization Demo in Angular using i18n</target>    
  8.         <context-group purpose="location">    
  9.           <context context-type="sourcefile">app/app.component.html</context>    
  10.           <context context-type="linenumber">1</context>    
  11.         </context-group>    
  12.       </trans-unit>    
  13.       <trans-unit id="myName" datatype="html">    
  14.         <source>Hello, My name is Ankit</source>    
  15.         <target>Hello, My name is Ankit</target>    
  16.         <context-group purpose="location">    
  17.           <context context-type="sourcefile">app/app.component.html</context>    
  18.           <context context-type="linenumber">5</context>    
  19.         </context-group>    
  20.       </trans-unit>    
  21.     </body>    
  22.   </file>    
  23. </xliff>   

Configure the app to serve in multiple language

 
Open angular.json file and add the following configuration.
  1. "build": {    
  2.   ...    
  3.   "configurations": {    
  4.     ...    
  5.     "es": {    
  6.       "aot"true,    
  7.       "i18nFile""src/translate/messages.es.xlf",    
  8.       "i18nFormat""xlf",    
  9.       "i18nLocale""es",    
  10.       "i18nMissingTranslation""error"    
  11.     }    
  12.   }    
  13. },    
  14. "serve": {    
  15.   ...    
  16.   "configurations": {    
  17.     ...    
  18.     "es": {    
  19.       "browserTarget""i18nDemo:build:es"    
  20.     }    
  21.   }    
  22. }    
Here we have added the configuration for Spanish language. We have provided the path and format for i18n file and set the locale to “es”. When we execute the application, app content will be served from the i18n file path provided.
 
Similarly, you can add configuration for other languages.
 

Execution Demo

 
Once you have added the configuration for all the languages in angular.json file, run the following command to start the server.
  1. ng serve --configuration=es  
This will launch the application in “es” configuration and our app will show the Spanish language translations.
 
Refer to the output screen as shown below:
 
Localization In Angular With i18n 
 
The configurations that we have defined will only help the app to run in the local machine. We cannot change the configuration once the app is launched.
 
A production app will need the application to serve for different language just by changing the URL. e.g. mywebsite.com/es will provide the Spanish version of site and mywebsite.com/en will provide the English version. In this case, the app will be served from different virtual directories for different language. We will explore how to do this in next section.
 

Modify the app component for production

 
Open app.component.ts and put in the following code.
  1. import { Component, LOCALE_ID, Inject } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8. export class AppComponent {  
  9.   title = 'i18nDemo';  
  10.   
  11.   languageList = [  
  12.     { code: 'en', label: 'English' },  
  13.     { code: 'hi', label: 'हिंदी' },  
  14.     { code: 'es', label: 'Espanol' }  
  15.   
  16.   ];  
  17.   
  18.   constructor(@Inject(LOCALE_ID) protected localeId: string) { }  
  19. }  
Here we have defined a list of languages and its locale code. These locale codes are standard codes. You can easily get list of language and the corresponding locale code by a simple Google search.
 
Add the following codes in app.component.html file.
  1. <ng-container *ngFor="let language of languageList">  
  2.   <a href="/{{language.code}}/"><button class="button">{{language.label}}</button></a>  
  3. </ng-container>  
Here we have defined three buttons for three languages. On each button click, the locale id will change and the locale id will be appended to URL also. This will allow us to serve the application from different directory.
 
Put the following code in app.component.css file to apply styles to these buttons.
  1. .button {  
  2.   background-color: darkslateblue;  
  3.   border-radius: 5px;  
  4.   colorwhite;  
  5.   padding5px;  
  6.   width10%;  
  7.   margin5px;  
  8.   text-decorationnone;  
  9.   cursorpointer;  
  10. }  

Script to compile the app for production

 
We need to have three different serving locations for three different languages. To build the application package for one language for production we will use the following command:
  1. ng build --prod --i18n-locale es --i18n-format xlf --i18n-file src/translate/messages.es.xlf --output-path=dist/es --baseHref /es/  
Let us understand this command. We provided the locale id for package, which is “es” for Spanish. We also provide the i18n file path and format. The output path property is required to provide the location for application package. The baseHref property specifies the base URL from which this package will be served.
 
We need to run this command for every language we will provide by changing the i18n file path and baseHref attribute values. However, this will be a cumbersome task if we have a lot of languages. Therefore, we will write a script to generate package for all language. Open package.json file and add the following scripts inside the “scripts” section.
  1. "build-locale:en": "ng build --prod --i18n-locale en --i18n-format xlf --i18n-file src/translate/messages.en.xlf --output-path=dist/en --baseHref /en/",  
  2. "build-locale:es": "ng build --prod --i18n-locale es --i18n-format xlf --i18n-file src/translate/messages.es.xlf --output-path=dist/es --baseHref /es/",  
  3. "build-locale:hi": " ng build --prod --i18n-locale hi --i18n-format xlf --i18n-file src/translate/messages.hi.xlf --output-path=dist/hi --baseHref /hi/",  
  4. "build-locale": "npm run build-locale:en && npm run build-locale:es && npm run build-locale:hi"  
Here we have created three scripts for three languages we are using. The “build-locale” script will execute all of them at once. All these scripts are key-value pairs. The key names we are using here are customizable and you can use any name of your choice. To create the application package for all the language, run the following command:
  1. npm run build-locale  
On successful execution, it will create a “dist” folder in the application’s root folder. The dist folder has three sub-folders to serve our application in three different languages. Refer to the image shown below: 
 
Localization In Angular With i18n 
 

Deploying the application on Firebase

 
We will deploy this application on Firebase to see the language change in real-time. Refer to my article Hosting A Blazor Application on Firebase and follow the steps mentioned to deploy this Angular app on Firebase.
 
Once the application is deployed, you will get the hosting URL. Open the URL and append the baseHref attribute as we defined earlier, to the URL. Hence, the URL will be yoursite.com/es/ for Spanish language and so on.
 
The application, which we built here, is hosted at https://i18ndemo-415ef.firebaseapp.com/en/. If you open this URL, you will see the output as shown below:
 
Localization In Angular With i18n 
 
Click on the links provided. The URL will change and the application will reload in a new language.
 

Conclusion

 
We learned how to internationalize our Angular app using i18n tools. We also applied localization to Angular application. Localization allows us to serve our app in different language, which helps in extending the reach to a worldwide audience. We learned how localization works in a production environment by deploying our application on Firebase.
 
Get the source code from GitHub and play around for a better understanding.
 
You can also read my other articles on my blog here.
 

See Also

Watch here a full video on how we can do Internationlization in Angular .