Memo Decorator
- It is an open-source platform that enhances the caching of pipe’s transform() function.
- It works with only primitive value types.
- It checks the value being passed and catches the response. If the same values are passed again, it will return the calculation from the cached result.
- It is extremely helpful when complex logic is being calculated based on the table’s rows. Using these decorators, we can completely avoid the duplicate for the same input again and again.
- npm i memo-decorator --save
- ng g p salaryCalculation
- ng g p dateFormat
- import memo from 'memo-decorator';
- import { Pipe, PipeTransform } from '@angular/core';
- import memo from 'memo-decorator';
- @Pipe({
- name: 'salaryCalculation'
- })
- export class SalaryCalculationPipe implements PipeTransform {
- @memo()
- transform(month: number): number {
- return this.getSalary(month);
- }
- getSalary(month: number) {
- console.log('memo pipe called');
- return month * 4000;
- }
- }
- import { Pipe, PipeTransform } from '@angular/core';
- import { DatePipe } from '@angular/common';
- @Pipe({
- name: 'dateFormat'
- })
- export class DateFormatPipe implements PipeTransform {
- transform(date: Date): any {
- console.log('DateFormatPipe called');
- const datePipe = new DatePipe('en-US');
- return datePipe.transform(date, 'dd/MM/yyyy');
- }
- }
- sampleData: { name: string; month: number; ViewDate: Date }[];
- ngOnInit() {
- this.sampleData = [{name: 'Rahul', month: 5, ViewDate: new Date() },
- {name: 'Rajendra', month: 2, ViewDate: new Date()},
- {name: 'Annu', month: 9, ViewDate: new Date()},
- {name: 'Aishu', month: 3, ViewDate: new Date()},
- {name: 'Raj', month: 5, ViewDate: new Date()}
- ];
- }
Step 5
- <div clas="row">
- <ul *ngIf="sampleData">
- <li *ngFor="let user of sampleData">
- <p>{{ user.name }} - {{ user.month | salaryCalculation }} - {{user.ViewDate| dateFormat}}</p>
- </li>
- </ul>
- </div>
In this poc, I have a small array object with some data as you can see in step 4 - basic name, month, and date. Here, I'm going to apply the pipes which we created above and find out the difference and benefits of using memo decorators. Let's run it and see the output. I have added a console log to each pipe to see how many times it's called.


Join the conversation! Your thoughts help the community grow.