Angular2 i18n - How to get a translation using code

I could not find the documentation in i18n (for Angular2) that goes beyond displaying translated text in HTML. I need to do to get the translated text directly in my code. In Angular 1, using the ng-translate function, it was easy to get it using the $ translate service. I can’t find the equivalent in the new i18n for Angular 2. Am I missing something?

+5
source share
2 answers

This is the link to the github question about i18n plans:

https://github.com/angular/angular/issues/9104

06-11-2016 @ zh99998 asked:

How to get i18n string in script? eg:

let _THIS_IS_A_I18N_STRING = ??? alert(_THIS_IS_A_I18N_STRING);

and @vicb (angular2 member) said:

@ zh99998 @marcalj This is not possible with the current impl. Could you create the correct function request in the problem tracker by filling out the problem template and adding use cases (and a link to others if applicable).

Thanks.

It seems that there is currently no way to use translations in code.

Although, there is a library for angular2 similar to $translate :

https://github.com/ocombe/ng2-translate

Usage similar to $translate (from docs):

 translate.get('HELLO', {value: 'world'}).subscribe((res: string) => { console.log(res); //=> 'hello world' }); 

Usage similar to translate filter (from docs):

<div>{{ 'HELLO' | translate:param }}</div>

In my case (ng1 / ng2 hybrid app) this was the best solution since I can use the same translation files for both versions of angular.

0
source

I was looking for the same topic. Angular i18n doesn't seem to support the use of off-the-shelf behavior to translate a string into ts code.

https://github.com/angular/angular/issues/11405

We introduced the translation service and used the pipe together. There are other libraries, for example. ngx-translate use translation in the source code. Below is the Angular design document on i18n.

https://docs.google.com/document/d/1LH7lJ1GjRgpGUjzNb6Eg4xrPooRdi80QOTYYh8z_JyY/edit#

In the Prior Art chapter, some libraries are listed in the table for comparison, but none of them support AOT.

0
source

Source: https://habr.com/ru/post/1261207/


All Articles