Multilingual Support in ASP.NET Using AngularJS
Internationalization (i8n) in AngularJS can be tricky when using it along with ASP.NET, but here's how you can get it done with no trouble at all.
Join the DZone community and get the full member experience.Join For Free
In this post we will see how we can add a multilingual support in ASP.Net web applications when using AngularJS as a front end framework.
In Angular we can use angular-translate to provide localization support in web applications. They maintain a translation table in a json format and we can keep the name value pairs just like we used to do with resource files (.resx).
Below are the steps you can take to implement localization in SPA applications. I am assuming you will have the working Angular project ready in place and I will focus on the translation part only. If you want to start from the basics of setting AngularJS in ASP.NET application, you can go through the series of post I authored earlier on my blog i.e. http://ovaismehboob.wordpress.com and search angular
Following are the steps to configure translation in angular apps.
- Add the Angular Translate package from NuGet Package Manager. You can make an entry in bower.json if working on ASP.NET 5.
- Once this is added, you have to make an entry in BundleConfig.cs so this script will be loaded on startup.
- Define angular translate dependency 'pascalprecht.translate' in our main angular module.
- Once defined, we can now use it anywhere in the view
- Below is the syntax when calling translation names/keys using filters
- Syntax when using with directives
- Run the application and you will see as preferred language was set “en” it will render the text in English
- Setting preferred language to Arabic will show Arabic text
- And with Spanish shows as belowThis is a basic example to maintain translation table for different languages. To make it more structured we can keep different .json files for each language
- In order to do so, let’s add 3 json files and name it lang_en.json, lang_ar.json and lang_sp.json.
- After creating just copy the json string of key value pairs defined in your main app above and paste it like the sample shown below for Arabic.
- We have to now use static file loader package to load our language files in json format. Static file loader script can be downloaded from https://cdnjs.com/libraries/angular-translate-loader-static-files.
- Make an entry in BundleConfig.cs file
- And finally, we can add resource files using useStaticFilesLoader method
- Hope this helps!
Opinions expressed by DZone contributors are their own.