Memo Decorator
What is 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.
For more details, please check here.
Let's jump into the code part and see how it works. Follow the steps mentioned below.
Step 1
Install the NPM package.
- npm i memo-decorator --save
Step 2
Create two pipes to demonstrate the difference between a normal pipe and the memo pipe.
- ng g p salaryCalculation
- ng g p dateFormat
- import memo from 'memo-decorator';
Step 3
Now, add some logic to your pipe, as below, with 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;
- }
- }
This is the code for the other pipe without memo decorator; just understand the difference between it and the memo pipe.
- 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');
- }
- }


Join the conversation! Your thoughts help the community grow.