Angular Memoize Pipe - fn pipe for template performance

June 28, 2026 · View on GitHub

clone-alert npm version

@ngx-rock/memoize-pipe is a small standalone Angular pipe for calling functions from templates without re-running them on every change detection pass.

It provides one pipe, fn, that lets Angular treat a template function call like a pure pipe binding. When the function reference and arguments stay unchanged, Angular keeps the previous pipe result and does not call the function again.

At A Glance

  • Package: @ngx-rock/memoize-pipe
  • Export: FnPipe
  • Template syntax: {{ myFunction | fn : arg1 : arg2 }}
  • Purpose: avoid repeated synchronous function calls in Angular templates when inputs are unchanged
  • Mechanism: Angular pure pipe change detection, not a custom global memoization cache
  • Best for: formatting, filtering, sorting, totals, and derived display values
  • Not for: async functions, side effects, hidden mutable state, or deep equality

Common search phrases this package answers:

  • Angular function in template performance
  • avoid calling method in Angular template
  • memoize Angular template function
  • Angular pure pipe for function calls
  • optimize Angular change detection in templates

Installation

npm install @ngx-rock/memoize-pipe
pnpm add @ngx-rock/memoize-pipe
yarn add @ngx-rock/memoize-pipe

Quick Usage

Import FnPipe into a standalone component and pass your function to the fn pipe.

import { Component } from '@angular/core';
import { FnPipe } from '@ngx-rock/memoize-pipe';

@Component({
  selector: 'app-total',
  standalone: true,
  imports: [FnPipe],
  template: `
    <strong>{{ calculateTotal | fn : items }}</strong>
  `
})
export class TotalComponent {
  items = [
    { price: 20, quantity: 2 },
    { price: 15, quantity: 1 }
  ];

  calculateTotal = (items: Array<{ price: number; quantity: number }>): number => {
    return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
  };
}

Before And After

Without the pipe, Angular can call a template method during every change detection cycle:

@Component({
  selector: 'app-user',
  template: `
    <div>{{ formatUser(user, preferences) }}</div>
  `
})
export class UserComponent {
  formatUser(user: User, preferences: UserPreferences): string {
    return `${user.name} (${preferences.theme})`;
  }
}

With fn, the function is called again only when the function reference or one of the pipe arguments changes:

import { FnPipe } from '@ngx-rock/memoize-pipe';

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [FnPipe],
  template: `
    <div>{{ formatUser | fn : user : preferences }}</div>
  `
})
export class UserComponent {
  formatUser = (user: User, preferences: UserPreferences): string => {
    return `${user.name} (${preferences.theme})`;
  };
}

What It Does

FnPipe helps with expensive synchronous computations in Angular templates:

  • formatting values from several inputs
  • calculating totals
  • sorting or filtering already-loaded arrays
  • mapping view models for display
  • avoiding repeated method calls during change detection

It is intentionally tiny. The package exports a standalone Angular pipe named fn.

How It Works

FnPipe relies on Angular pure pipe behavior.

Angular pipes are pure by default. For a pure pipe binding, Angular calls transform only when an input changes by reference. This means:

  • primitive arguments are compared by value
  • objects and arrays are compared by reference
  • the function itself is also an input, so keep its reference stable
  • there is no global cache and no deep equality check

This is why arrow function properties are recommended. They keep the function reference stable and preserve this.

export class ExampleComponent {
  multiplier = 10;

  multiplyItems = (items: number[]): number[] => {
    return items.map(item => item * this.multiplier);
  };
}
{{ multiplyItems | fn : items }}

More Examples

Multiple Arguments

formatPrice = (amount: number, currency: string, locale: string): string => {
  return new Intl.NumberFormat(locale, {
    style: 'currency',
    currency
  }).format(amount);
};
{{ formatPrice | fn : total : 'USD' : 'en-US' }}

Filtering A List

filterUsers = (users: User[], query: string): User[] => {
  const normalizedQuery = query.trim().toLowerCase();

  if (!normalizedQuery) {
    return users;
  }

  return users.filter(user => user.name.toLowerCase().includes(normalizedQuery));
};
@for (user of filterUsers | fn : users : searchQuery; track user.id) {
  <span>{{ user.name }}</span>
}

Create a new users array when the list changes. Mutating the same array in place will not trigger a pure pipe recalculation.

Mapping Display Data

toUserLabel = (user: User, roleNames: Record<string, string>): string => {
  return `${user.name} - ${roleNames[user.role] ?? 'Unknown role'}`;
};
{{ toUserLabel | fn : user : roleNames }}

Using With Module-Based Angular Apps

import { NgModule } from '@angular/core';
import { FnPipe } from '@ngx-rock/memoize-pipe';

@NgModule({
  imports: [FnPipe]
})
export class AppModule {}

When To Use It

Use fn when:

  • the function is synchronous
  • the function is pure for the same inputs
  • the computation is expensive enough to matter
  • the arguments use immutable updates or stable references
  • creating a dedicated custom pipe would be unnecessary overhead

When Not To Use It

Do not use fn when:

  • the function has side effects
  • the function depends on hidden mutable state
  • the function returns different results for the same inputs
  • the operation is asynchronous
  • a dedicated domain pipe would make the template clearer

For asynchronous work, use Angular's async pipe with an Observable, Promise, or signal-based state.

Notes

Stable Function References

Prefer arrow function properties:

formatName = (user: User): string => {
  return `${user.firstName} ${user.lastName}`;
};

Avoid creating functions inline in the template or returning a new function from a getter.

Reference Types

Objects and arrays are compared by reference. If an object or array changes, create a new instance:

this.items = [...this.items, newItem];

Avoid in-place mutation if you expect the pipe to recalculate:

this.items.push(newItem);

FAQ

Does this pipe implement its own memoization cache?
No. It uses Angular pure pipe caching for the current binding. Angular skips the pipe call while the function reference and arguments stay unchanged.

Can I use it with async functions?
No. fn is designed for synchronous functions. Use Angular's async pipe for async values.

Does it do deep equality for objects and arrays?
No. Angular pure pipes use reference checks for objects and arrays.

Is it tree-shakable?
Yes. The package has no side effects and exports a standalone pipe.


English | Русский