Shiva Nayak Dharavath
Shiva Nayak Dharavath

Reputation: 3172

how to avoid multiple executions of a impure pipe in angular 2?

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;
        }
    }

Upvotes: 5

Views: 1494

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657546

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.

Upvotes: 4

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

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().

Upvotes: 2

Related Questions