In Angular Ivy, why pure pipe instance is not cached between usages like in View Engine?

Viewed 253

As I tried to explore source code of pipe implementation in Ivy, I figured out that in Ivy, if a pure pipe is used in multiple places in a component template, Angular will create each instance for the same pure pipe.

In View Engine, pure pipe instance is cached between usages (ref https://indepth.dev/posts/1061/the-essential-difference-between-pure-and-impure-pipes-in-angular-and-why-that-matters)

So, could you please explain me in Ivy why don't we cache pure pipe instance as implemented in View Engine?

I just made a simple comparison just FYI, the difference can be seen in console log

Thanks a lot!

https://stackblitz.com/edit/angular-ivy-pure-pipe?file=src/app/app.component.html and

https://stackblitz.com/edit/angular-view-engine-pure-pipe?file=src/app/app.component.html

1 Answers

Making PURE Pipes as multi-instance Angular allows injecting parent directives.

<div  appCustomDir> <!-- appCustomDir is a user defined directive  -->
    <div>
        {{result | custom: number1 : number2}} <!-- custom is a user defined pipe -->
    </div>
</div>

Now we can Inject this "appCustomDir" inside our pipe constructor in our "custom" pipe like below-

import { CustomDirDirective } from './../customDirectives/custom-dir.directive';
import { Inject, Optional, Pipe, PipeTransform } from '@angular/core';
    @Pipe({
  name: 'custom',
  pure: true
})
export class CustomPipe implements PipeTransform {

constructor(@Optional() @Inject(CustomDirDirective) private customDir) {}

transform(value: unknown, ...args: number[]): unknown {
    if(this.customDir) {
  this.customDir.changeborder();
}
    this.customDir.changeborder();
    return args.reduce((n, ac = 0) => ac + n);
}
}

Now prior to IVY engine, there was VIEW engine used by angular, the VIEW engine only created 1 instance of PURE pipe and shared it across multiple uses. But IVY created multi instances of PURE pipes, so we can inject parent directives.

Try - make "enableIvy": false in tsconfig.json and try to inject parent directive as above, it will give you an error.

Related