Reputation: 649
I am translating my Angular 7 app using i18n and I have custom pipes that produce text. How can I translate the text produced by the pipes?
I stick to the i18n guideline provided by the angular docs, I use this xliff merge strategy for development and I use this tutorial for my builds per locale.
For example, I am trying to translate this time ago pipe in which numbers are converted to text.
At the moment I have no idea how to translate custom pipes. I only know how to translate html tags using the i18n
attribute, which does not seem to be applicable to the custom pipes that I use.
This angular i18n paragraph suggests to set a some kind of global variable in the main app.module.ts
, but the examples are a bit scarce and (a) I don't know how to set the locale depending on the build per language as I do following this tutorial, (b) I don't know how to get the global locale into my custom pipe and (c) is it possible translate the contents for the pipe in the messages.<locale>.xlf
files instead of within the pipe?
Upvotes: 1
Views: 4128
Reputation: 1882
Usually what you can do in this situation, is add the translateService as a dependency into your pipe, and just translate from code.
So your constructor in the pipe would look like:
constructor(private changeDetectorRef: ChangeDetectorRef, private ngZone: NgZone, private tr: TranslateService) {}
And in your transform function you can return the text value with this:
// [...]
} else if (days <= 545) {
return this.tr.instant('time.one-year-ago');
} else { // (days > 545)
return this.tr.instant('time.years-ago', { years });
}
// [...]
Upvotes: 1