Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a pipe under a different name

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)
like image 666
tom Avatar asked Oct 16 '25 01:10

tom


1 Answers

You can just wrap the original pipe

@Pipe({name: 'i18n'})
export class I18nPipe implements PipeTransform {
  constructor(private translatePipe: TranslatePipe) {
  }

  transform(query: string, ...args: any[]) {
    return this.translatePipe.transform(query, args);
  }
}
like image 100
Diadistis Avatar answered Oct 18 '25 22:10

Diadistis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!