I need to Add multiple language support for my Angular 4 Application.I need to know the best approach to achieve this.
Angular Internationalizationlink Internationalization, sometimes referenced as i18n, is the process of designing and preparing your project for use in different locales around the world. Localization is the process of building versions of your project for different locales.
AngularJS supports inbuilt internationalization for three types of filters currency, date and numbers. We only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser.
You can use ngx-translate which is the standard library for internationalization in Angular 2+
You can import the library and create a set of json files which contains the translations and put it inside the assets folder.
Then you can refer it in the HTML. say for example.
en.json
has,
"guest.first-name": "first Name",
where first one is the key and second is the value to be displayed . and you can refer in the html as,
<input [label]="'guest.first-name' | translate" type="text" name="form_name" [(ngModel)]="firstName" required="required" ></input>
You can use ngx-translate library that I used it and it is very useful for internationalization for Angular.Also I advice you about Angular, you should check jhipster project and then you can learn more advance and detail topics about Angular 4 and Spring Boot.It is very useful project and also you can create Angular and Spring Boot project rapidly...
if you use angular-cli to create newApp it has a good infrastructure for translate, that use ngx-translate. and for translate your text use pipe: translate like:
<span>{{ text | translate }}</span>
translate files exist on the /src/assets/i18n/langCode.json (forEx: en.json). and an initializing require in the main layout constructor
constructor(public translate: TranslateService, zone: NgZone) {
translate.use('en');
}
You can do also a simple thing by making various files such as en.json etc. consisting of various lables such as
en.json
{
lbl_name1: "Lable Name 1",
lbl_name2: "Lable Name 2"
}
Now do a thing write a mechanism which will read the file,for Angular 6 we can use http client in an your abc.ts file & put the data into a session storage
public languageVar: any = [];
//Http Client can be used and you can pass the file name at runtime also, I have
passed it statically
this.httpClientObj.get(en.json).suscribe({
data=> {
//setting into session for further use into app
window.localstorage.setItem('langLables',JSON.stringify(data));
//setting into the variable declared above
this.languageVar = JSON.parse(window.getItem('langLables'));
},
error=>{
alert("File not found");
}
}
);
Now suppose you have an html file, abc.html, by using one-way binding
<h1>{{languageVar.lbl_name1}}</h1>
<p>{{languageVar.lbl_name2}}</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With