Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 i18n - How to get translation through code

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

like image 448
pierrebo Avatar asked Dec 13 '16 16:12

pierrebo


2 Answers

Perhaps this has been answered but the following did it for me.

import { TranslateService } from '@ngx-translate/core';


private translate: TranslateService;


const response= this.translate.instant('HELLO_WORLD');

It seems there are two methods for this:

  1. the get method returns an observable
  2. the instant method returns the translation directly. Only caveat, the instant method is synchronous

See notes on their documentation regarding the instant method. https://github.com/ngx-translate/core

This method is synchronous and the default file loader is asynchronous. You are responsible for knowing when your translations have been loaded and it is safe to use this method. If you are not sure then you should use the get method instead.

like image 126
tmez Avatar answered Nov 02 '22 04:11

tmez


Since Angular 9 there is an experimental and undocumented $localize tag function. It can be applied to a template string.

greetings = $localize`Hello ${this.world}!`;

Internationalization with @angular/localize

like image 24
oleg gabureac Avatar answered Nov 02 '22 02:11

oleg gabureac