Reputation: 334
As a beginner in Angular, I came across the pure pipes which
The object reference part I am clear with and the problem lies with the primitive types.
A crucial fact lies on optimization with pure pipe is
Angular is going to evaluate given pure pipe call only if it has received different arguments compared to its previous invocation.
I tried with an example:
applypure.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'applypure',
pure: true
})
export class ApplypurePipe implements PipeTransform {
count = 0;
constructor() {
// To determine an instance is created
console.log('pipe created:');
}
transform(value: number, exponent: number): number {
//this.count++;
console.log(value);
return Math.pow(value, exponent);;
}
}
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
{{12 | applypure : 2}}
{{12 | applypure: 2 }}
`
})
export class AppComponent {
}
}
The result is shown below :
The same input is being passed to pure pipe immediately after, yet its transform method is called twice. Shouldn't it skip the re-evaluation?. Please clarify.
Upvotes: 2
Views: 3166
Reputation: 334
I think I found the right expression !.
a) to make sharing/caching work I believe there should be only one pipe usage of the expression in the component. The transform function of the pure pipe wont re-evaluate for the immediate same input.
Eg. When you input 12 and enter, transform fn is invoked and if you immediately input 12 again the invocation of transform fn is skipped.
So in Pure Pipes, last Input to the piped expression will be checked and it's the criteria for a valid change detection to run when compared to immediate next inputs.
app.component.html
Type:
<input type="text" #box (keyup.enter)="addName(box.value); box.value=''" placeholder="Parameter">
<div *ngIf="number2">
{{number2 | applypure : 2}}
</div>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent {
number2: number;
addName(num: number) {
this.number2 = num;
console.log("Log at component: "+ this.number2);
}
}
Upvotes: 1
Reputation: 31815
There is no shared "cache" between pipes. The "caching" applies for every call in the template
Upvotes: 1
Reputation: 46
I believe this is happening because every time you use your pipe in the HTML it makes a call to the transform function. The pipe doesn't differ between the attributes you are passing to its function, according to the PipeTransform interface in the Angular repository:
Angular invokes the
transform
method with the value of a binding as the first argument, and any parameters as the second argument in list form.
Upvotes: -1