Complete the code to declare a pure pipe in Angular.
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'example', pure: [1] }) export class ExamplePipe implements PipeTransform { transform(value: string): string { return value.toUpperCase(); } }
Setting pure: true makes the pipe pure, so Angular caches its output and calls it only when input changes.
Complete the code to create an impure pipe in Angular.
@Pipe({
name: 'impureExample',
pure: [1]
})
export class ImpureExamplePipe implements PipeTransform {
transform(value: any): any {
return value;
}
}Setting pure: false makes the pipe impure, so Angular calls it on every change detection cycle.
Fix the error in the pipe transform method to avoid unnecessary recalculations.
transform(value: string): string {
if (value === this.previousValue) {
return [1];
}
this.previousValue = value;
return value.toLowerCase();
}Return the cached previous value to avoid recalculating when input hasn't changed.
Fill both blanks to create a pure pipe that only recalculates when input changes.
export class EfficientPipe implements PipeTransform { private lastValue: any; private lastResult: any; transform(value: any): any { if (value [1] this.lastValue) { return this.lastResult; } this.lastValue = value; this.lastResult = value [2] 10; return this.lastResult; } }
Use strict equality to check if input changed and add 10 to the value if changed.
Fill all three blanks to implement an impure pipe that recalculates on every change detection and logs the input.
export class LoggingPipe implements PipeTransform { transform(value: any): any { console.log([1]); const result = value [2] 5; return result [3] 2; } }
Log the input value, add 5, then multiply by 2 to produce the result.