I'm using the ngx-translate internationalization library in my Angular 6 app. Right now a translation in one of my templates is done like this:
<span>{{ 'HELLO' | translate:param }}</span>
However, it would be great if I could have it this way:
<span>{{ 'HELLO' | i18n:param }}</span>
All I have to do is somehow give the pipe a name alias, but I have no idea how to accomplish that. I started to write something like...
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Pipe({ name: 'i18n' })
export class I18nPipe implements PipeTransform {
constructor(private i18n: TranslateService) { }
transform(key: string, ...args: any[]): any {
this.i18n.get(key).subscribe((res: string) => {
return res || key;
});
}
// How to return if async? How to process args?
}
But should I even code it this way, or is there maybe a simple general way in Angular to alias pipes?
Another way I tried:
import { Pipe, PipeTransform } from '@angular/core';
import { TranslatePipe } from '@ngx-translate/core';
@Pipe({ name: 'i18n' })
export class I18nPipe extends TranslatePipe implements PipeTransform {
transform(key: string, args?: any): any {
return super.transform(key, args);
}
}
This gives me an error:
ERROR TypeError: Cannot read property 'get' of undefined
at I18nPipe.updateValue (ngx-translate-core.js:1058)
at I18nPipe.transform (ngx-translate-core.js:1097)
at I18nPipe.transform (i18n.pipe.ts:8)
You can extend the original pipe, without adding any implementation code:
import { Pipe } from '@angular/core';
import { TranslatePipe } from '@ngx-translate/core';
@Pipe({ name: 'i18n' })
export class I18nPipe extends TranslatePipe { }
See this stackblitz for a demo.