Internationalization with Angular 4

后端 未结 4 854
有刺的猬
有刺的猬 2020-12-10 17:01

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

相关标签:
4条回答
  • 2020-12-10 17:14

    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>
    
    0 讨论(0)
  • 2020-12-10 17:19

    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>
    
    0 讨论(0)
  • 2020-12-10 17:19

    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');
    }
    
    0 讨论(0)
  • 2020-12-10 17:33

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

    0 讨论(0)
提交回复
热议问题