Tuesday, 15 May, 2018 UTC


Summary

I always worked with ngx-translate  a fantastic library that help you a lot to translate your angular application.
However today after Angular 6 and the new cli has been released I decided to give a try to i18n.
At the beginning I struggle a bit to make everything working but thanks to @ocombe I easily create a good Proof Of Concept to start on.
I try to summarize the steps that you need to perform to make it working:
Requirements:
– node >= 8
– angular/@cli 6.0.1
The first step we need to perform is to install/upgrade angular/@cli
npm install -g @angular/[email protected]
then we can generate our new project:
ng new translations-prj
You’ll be surprised how fast it’s now to install all the dependencies
Now that our project is ready to use open the app.component.html in src/app. Remove the content and just add:
———–
<div>
<h1 i18n>Hello</h1>
</div>
———–
The only “weird” part is `i18n` that tell angular to translate this sentence.
In the terminal now we can run:
ng xi18n –i18n-locale en
this will generate a file called: message.xlf
then inside src create a new folder called locale and copy the message.xlf renaming it in:
messages.fr.xlf
Do not change anything inside but after the source tag add:
<source>Hello World</source>
   <target>Bonjour!</target>
….
</source>
Now that we got the French one we can try to add another language and of course I decided to create the Italian one ;).
Inside the same folder (locale) copy messages.fr.xlf and create:
  • messages.it.xlf
This time we just need to change the translation:
<target>Buongiorno</target>
We almost done the last step is the angular.json file (I can say the trickiest part)
404: Not Found
(https://gist.github.com/daniele-zurico/77f7c47b5455f178aa09468d74982762)
You’ll see there 2 changes from the basic file generated by the cli under:
  • build > configurations
  • serve > configuration.
Copy them and now you can see the final result just running:
ng serve –configuration=it
or
ng serve –configuration=fr
and if you need a production build:
ng build –configuration=fr
or
ng build –configuration=it
for more specific use cases refer to the angular documentation
If you enjoyed this post follow me on twitter @Dzurico
The post i18n with Angular 6+ appeared first on Angular and Javascript blog.