Ben Taliadoros
Ben Taliadoros

Reputation: 9511

How to create new ngx-translate pipe (pure vs impure)

Edit: I want to basically extend the pipe provided by ngx-translate, as below:

import { Pipe, PipeTransform } from '@angular/core';
import { TranslatePipe } from "@ngx-translate/core";

@Pipe({
  name: 'msg'
})

export class MsgPipe extends TranslatePipe implements PipeTransform {
  transform(value: any, args: any[]): any {
    return super.transform(value, args)
  }
}

This works only when pure is set to false, so I think the loader for ngx-translate is not ready yet. Is there anyway of checking? This way I could keep the pipe pure and working.

Original post (not relevant):

I have created a pipe that simply calls translateService.instant and returns the result.

@Pipe({
  name: 'msg',
  pure: false
})
export class MsgPipe implements PipeTransform {

  constructor(private translateService: TranslateService) {}

  transform(value: any, args: any[]): any {
    console.log('checked. val = ', value)
    return this.translateService.instant(value, args);
  }
}

Without marking this as pure: false, the pipe just returns the value. With it it does (as I presume the file loader is finished).

My issue is that each pipe is called about 8 times, can I do anything with change detection to tell the pipe to stop checking once a value is retrieved?

Upvotes: 0

Views: 4435

Answers (1)

That White Eyebrow Guy
That White Eyebrow Guy

Reputation: 569

The problem of being triggered multiple times is the reason why you want a pure pipe, as this only gets triggered again when the input reference changes (1). The problem with translate service instant though is, that at the time you try to load something, the translation might not be there yet so a pure pipe will not help you.

For ngx-translate, there is a pipe already which you can use, namely the translate pipe (2).

As far as I know, you can't do anything with the pipe to make it stop reevaluating itself. For this you might want to set your component to OnPush so it only updates itself when one of it's inputs change.

(1) https://angular.io/guide/pipes#pure-and-impure-pipes

(2) https://github.com/ngx-translate/core/blob/master/src/translate.pipe.ts

Upvotes: 2

Related Questions