Hello guys, the other day in my job I had to add multilanguage support to our current Angular App that we are developing, was the first time I had to include this kind of feature to an Angular App, so I had to investigate how to do this implementation and I thought that was amazing share that I learn with you.
First, we need to include the @angular/localize to our angular application.
ng add @angular/localize
We can configure all i18n settings in angular.json
"projects": {
"angular-localize-example": {
................................................
"i18n": {
"sourceLocale": "en-US",
"locales": {
"es": {
"translation": "src/locale/messages.es.xlf"
}
}
},
................................................
In the "sourceLocale" attribute, we can specify the default language that our application will use, in this case "en-US". In the "locales" attribute we will define the language that our application will support, for example Spanish "es" and the path of the translation file, usually in "src/locale" folder.
The next step is adding the i18n attribute to the HTML where we want to add a translatable text.
<p i18n>Welcome to my app!</p>
Once we have finished placing the attributes where we want. We had to extract the translations with the next command
ng extract-i18n --output-path src/locale
The --output-path parameter specified where will store the generated translation file.
If we open the generated messages.xlf file, we will see something like next
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en-US" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="856378210155557077" datatype="html">
<source>Welcome to my app!</source>
<context-group purpose="location">
<context context-type="sourcefile">src/app/app.component.html</context>
<context context-type="linenumber">1</context>
</context-group>
</trans-unit>
</body>
</file>
</xliff>
Now we can copy the file and renamed it like we indicated in angular.json. For the Spanish translation will be messages.es.xlf and edit the text with the translation.
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="es" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="856378210155557077" datatype="html">
<source>¡Bienvenidos a mi APP!</source>
<context-group purpose="location">
<context context-type="sourcefile">src/app/app.component.html</context>
<context context-type="linenumber">1</context>
</context-group>
</trans-unit>
</body>
</file>
</xliff>
When we will have all ready we can build our application, but with one new parameter
ng build --localize
This will generate the build app but separated in the languages that our application support.
Full Code
https://github.com/davidzcode/angular-localize-example
Top comments (0)