Chanaka Fernando
Chanaka Fernando

Reputation: 2335

Internationalization with Angular 4

I need to Add multiple language support for my Angular 4 Application.I need to know the best approach to achieve this.

Upvotes: 7

Views: 2601

Answers (4)

Ashish Devade
Ashish Devade

Reputation: 37

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>

Upvotes: 1

hamid_reza hobab
hamid_reza hobab

Reputation: 929

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');
}

Upvotes: 2

caglarturkurka
caglarturkurka

Reputation: 116

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...

Upvotes: 3

Sajeetharan
Sajeetharan

Reputation: 222712

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>

Upvotes: 6

Related Questions