typescript
47 lines · 8 steps
Building a cached money pipe in Angular
A standalone Angular pipe that formats currency with Intl.NumberFormat and memoizes formatters by locale and options.
Explained by
highlit
1import { Pipe, PipeTransform, Inject, LOCALE_ID } from '@angular/core';
2
3interface MoneyOptions {
4 currency?: string;
5 display?: 'symbol' | 'code' | 'name';
6 minimumFractionDigits?: number;
7}
8
9@Pipe({
10 name: 'money',
11 standalone: true,
12})
13export class MoneyPipe implements PipeTransform {
14 private readonly formatters = new Map<string, Intl.NumberFormat>();
15
16 constructor(@Inject(LOCALE_ID) private readonly locale: string) {}
17
18 transform(
19 value: number | string | null | undefined,
20 options: MoneyOptions = {},
21 ): string {
22 if (value == null || value === '') {
23 return '';
24 }
25
26 const amount = typeof value === 'string' ? Number(value) : value;
27 if (Number.isNaN(amount)) {
28 return '';
29 }
30
31 const { currency = 'USD', display = 'symbol', minimumFractionDigits } = options;
32 const cacheKey = `${this.locale}|${currency}|${display}|${minimumFractionDigits ?? ''}`;
33
34 let formatter = this.formatters.get(cacheKey);
35 if (!formatter) {
36 formatter = new Intl.NumberFormat(this.locale, {
37 style: 'currency',
38 currency,
39 currencyDisplay: display,
40 minimumFractionDigits,
41 });
42 this.formatters.set(cacheKey, formatter);
43 }
44
45 return formatter.format(amount);
46 }
47}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Caching expensive-to-construct objects like Intl.NumberFormat by a composite key avoids rebuilding them on every change-detection pass.
- 2Guarding against null, empty, and NaN inputs keeps a pipe safe to bind directly to raw template data.
- 3Injecting LOCALE_ID lets formatting follow the app's configured locale instead of a hardcoded default.
Related explainers
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-cached-money-pipe-in-angular-explained-typescript-1396/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.