Angular 5 internationalization
Asked Answered
I

3

47

I'm building an application using the latest Angular5 and what I need is for a user to be able to switch languages. I've never had to implement this in an Angular2+ (actually I'm using Angular5).

I need to set translations in two places:

  • Component's template html - change labels to the specified language
  • In code in the component.ts file - I may need to translate some strings that are built dynamically under particular conditions in the code

I was looking at ngx-translation and it looks to do everything I need, as in it allows you to change language without rebuilding your code, see here. However I read it was probably going to be deprecated due to the main developer moving to the angular team to develop their i18n code.

I also understand that the current i18n doesn't support everything I need right now, see here.

My question - what is the state of play for translations in the latest version of Angular? Are there other libraries people would recommend instead, if indeed, Angular itself hasn't got full support as of yet (for changing language without recompiling)? Is ngx-translate good for the future?

Any guidance in this area is greatly appreciated!

Ironsmith answered 15/11, 2017 at 16:47 Comment(0)
I
57

After spending time looking into this, I thought I'd post the main differences I found between ngx-translate and Angular-i18n:

  • Angular only works with one language at a time, you have to completely reload the application to change the lang. The JIT support only means that it works with JIT, but you still have to provide the translations at bootstrap because it will replace the text in your templates during the compilation whereas this lib uses bindings, which means that you can change the translations at any time. The downside is that bindings take memory, so the Angular way is more performant. But if you use OnPush for your components you will probably never notice the difference
  • Angular only supports using i18n in your templates for now, I'm working on the feature that will allow you to use it in your code, but it's still a work in progress. This lib works both in code and templates
  • Angular supports either XLIFF or XMB (both are XML formats), whereas this lib supports JSON by default but you can write your own loader to support any format that you want (there's a loader for PO files for example). Personally, Json files are quite straight forward to read through rather than these other formats, but that’s not a huge drawback.
  • Angular supports ICU expressions (plurals and select), but this library doesn't
  • Angular supports html placeholders including angular code, whereas this library only supports regular html (because it's executed at runtime, and not during compilation, and there is no $compile in Angular like there was in AngularJS)
  • The API of this library is more complete because it is executed at runtime it can offer more things (observables, events, ...) which Angular doesn't have (but doesn't really need given that you cannot change the translations) The creator of ngx-translate has said this:

Ocombe (developer of ngx): @josersleal that's exactly what they did, the angular team hired me to improve i18n for everyone But there is no way to integrate my lib directly into the core, after working for 3 months for the core team I can tell you that Angular i18n is much more complex and elaborate than my lib. It handles a lot of more complex stuff, and it does it without all the bugs and shortcomings that my lib has. I understand that it's frustrating that the core doesn't evolve as fast as what a library can do, but there are reasons for that, and the first one is that you cannot implement something and change it whenever you see that you forgot to include a use case. Everything has to be thoroughly planned and thought. Still, you will have most of the things that this lib can do in the core in the future, but it might take a year before we get there unfortunately. The good news is that it's going to be much better than my naive implementation.

This is a good article to discuss the main differences between ngx-translate and Angular’s i18n: https://github.com/ngx-translate/core/issues/495

The changes for i18n are due in version 6 of angular. Today, we are currently on version 5:

Some thoughts…

  • Angular-i18n is more performant as you compile your application in the language you require (rather than translations happening at runtime). Can also be a drawback as you may need to have multiple builds of your application in different languages.
  • If we were using SEO, angular-i18n would be the way forward, due to url browsing. For my case, I don’t need this at all.
  • If we required plural switching etc. Again, I don’t need this – I just need a fairly straight forward runtime language switch in templates and code.
  • Angular-i18n wont be released until March 2018 at least. For me I cant wait until then as I need to build my app now.
  • ngx-translate won’t have as comprehensive a set of capabilities as angular-i18n BUT again, I only need simple runtime translations, so think its fine for what we need.
  • ngx-translate is open source and come the day it’s no longer being developed, if there's a serious issue I guess I could fix myself (hopefully by the time that comes, any issues that may arise will be ironed out).

I am also going to have a look at the Angular-l10n library as it looks very good:

Ironsmith answered 17/11, 2017 at 13:54 Comment(4)
Have you checked on the current status of the official i18n? "Angular-i18n wont be released until March 2018 at least". Well, now is March 2018 already. Our team has still some time to decide which solution to take, but we don't want to wait forever. Is there a roadmap for i18n? the best reference I can find is Ocombe's commit history: github.com/angular/angular/commits?author=ocombe As I see it Angular will probably drop i18n sooner or later, as everybody uses the community solution instead and that gets updates more regularly.Carlenecarleton
NOTE: The ngx-translate package has been updated in the last couple of weeks to support Angular6Ironsmith
It should be noted that there is a possibility that development for ngx-translate could end in the future github.com/ngx-translate/core/issues/783Phalangeal
it's an old post now but excellent summary @RobMcCabe thanks!Titration
P
6

Yes. ngx-translate is good till now, and I hope it will be in future as well.

I am using ngx-translate in my current Angular 5 project with 5+ languages.

It is working fine for me so far. I did not have to make any custom changes, it worked like plug and play thing.

I used this plugin https://github.com/ngx-translate/core

Progressist answered 16/11, 2017 at 5:44 Comment(1)
Hmm - yea, agreed, ngx-translate is great! BUT I was hoping for something a bit firmer than "I hope it will be in the future" ;-) as I have to implement this todayIronsmith
S
4

Instead of using ng-translate you can use config file and language json files for that the you can place that json file in your server location and access it easily from angular

in config.json u can defile language type

{ 
  "LANGUAGE": "fr.json" 

}

in en/fr.json file

{
    "TITLE": "Bonjour Angular avec translate !",
    "SELECT": "Changer la langue"

}

config.json and language fils

hear is the sample code

App.component

export class AppComponent  {

  name =  LAN_CONFIG['TITLE'];
  // name =  APP_CONFIG['LANGUAGE'];
}

OR

You Can Use config.js file

add this code segment to index.html header section

<script>
    var xhrObj = new XMLHttpRequest();
    var url = '/assets/config/config.js';
    xhrObj.open('GET', url, false);
    xhrObj.send('');
    var se = document.createElement('script');
    se.type = "text/javascript";
    se.text = xhrObj.responseText;
    document.getElementsByTagName('head')[0].appendChild(se);
  </script>

config.js file

enter image description here

window.config= {};
window.config['LANGUAGE'] = 'er.js';

you can access that variable to access value using

@Injectable()
export class LanguageService {

  appConfig:AppConfigService;
  lanTypePath ='../../assets/i18n/'+ window['config'].LANGUAGE;
 constructor(private http: HttpClient)
  {
    console.log(APP_CONFIG['LANGUAGE']);
  }

  public load()
  {
    return new Promise((resolve, reject) => {

      this.http.get(this.lanTypePath).catch((error: any): any => {

        reject(true);
        return Observable.throw('Server error');
      }).subscribe((envResponse :any) => {
        let t = new LanConfig();
        //Modify envResponse here if needed (e.g. to ajust parameters for https,...)
        LAN_CONFIG = Object.assign(t, envResponse);
        resolve(true);
      });

    });
  }

}

think this method better than previous for your situation

Github demo

Hope this will helps..!

Storz answered 29/10, 2019 at 7:15 Comment(3)
awesome - can you change language on the fly with this approach?Ironsmith
Ya sure ,you should only have to change the language selection in config file fr.json to en.josonStorz
@RobMcCabe -change the answer for better way, think this answer will address your issueStorz

© 2022 - 2024 — McMap. All rights reserved.