5

Hi I am using Angular 2 pipe to return the keys of object, it is an impure pipe and It is being executed multiple times which is blocking some other script, how can I avoid multiple executions of the impure pipes? my code is as follows :

 import {Pipe,PipeTransform} from '@angular/core';
    @Pipe({ name: 'NgforObjPipe', pure: true })
    export class NgforObjPipe implements PipeTransform {
        transform(value, args:string[]):any {
        let keys = [];
        for (let key in value) {
            keys.push({key: key, value: value[key]});
        }
        console.log('pipeeeeeeeeeeeeeee', keys);
        return keys;
        }
    }
Shiva Nayak Dharavath
  • 3,082
  • 1
  • 14
  • 19
  • In what sense is this pipe impure? Since you are specifying `pure: true`, why do you think this is a problem? –  Jul 25 '17 at 05:38

2 Answers2

4

There is no way to prevent that. That's what an impure pipe is for.

What you can do is, to ensure that as little work is done inside the the transform() method as possible, for example by caching results and only recalculate when the passed value has actually changed.

You can also use Object.keys() to get more efficient code. See also How to iterate [object object] using *ngFor in Angular 2

ChangeDetectionStrategy.OnPush can be used to reduce the number of times change detection is run, to minimize the number of calls to the pipe.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
2

There could be two ways of doing this.

  1. You could consider passing this Object value as Input to component and make your component ChangeDetectionStrategy onPush.
  2. Apply your NgforObjPipe Pipe over collection from component itself by calling its transform method manually like NgforObjPipe.tranform().
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299