Pipes: Built-in and Custom
Transforming displayed values with built-in pipes and writing a simple custom pipe.
What you'll learn
- Use a built-in pipe (e.g. uppercase, date) in a template expression
- Chain multiple pipes together
- Write a simple custom pipe's transform() method
Explanation
A pipe transforms a displayed value directly in a template expression, using the | syntax: {{ name | uppercase }} displays name converted to uppercase, without changing the underlying name property itself. Angular ships several built-in pipes: uppercase/lowercase, date (formats a Date value), currency, json (useful for debugging, printing an object's JSON representation).
Pipes chain: {{ price | currency | uppercase }} applies currency first, then uppercase to its result, left to right.
A custom pipe is a class decorated with @Pipe({ name: "myPipe" }) implementing PipeTransform's single required method, transform(value, ...args): for example, a pipe that truncates long text:
@Pipe({ name: "truncate" })
export class TruncatePipe implements PipeTransform {
transform(value: string, maxLength: number): string {
return value.length > maxLength ? value.slice(0, maxLength) + "…" : value;
}
}
used as {{ description | truncate:50 }}, where 50 is passed as transform's second argument.
Guided lab
Predict: A custom pipe's transform() method
Read this custom pipe implementation and predict what it returns for both calls.
class TruncatePipe {
transform(value: string, maxLength: number): string {
return value.length > maxLength ? value.slice(0, maxLength) + "…" : value;
}
}
const pipe = new TruncatePipe();
console.log(pipe.transform("A short description", 50));
console.log(pipe.transform("This is a genuinely much longer description that exceeds the limit", 20));Stuck? Get a hint.
Common mistakes
- Assuming a pipe mutates the underlying data -- it only transforms what's displayed, leaving the original property value unchanged.
- Getting the chain order wrong, forgetting pipes apply strictly left to right.
- Forgetting a custom pipe's transform() method's extra arguments come from the pipe's own syntax after the colon (e.g. :50), not from anywhere else.
Knowledge check
Takeaway
Pipes transform displayed values without mutating underlying data, chain left to right, and a custom pipe just implements transform().
Summary
Built-in pipes (uppercase, date, currency, json) and custom pipes (implementing PipeTransform.transform()) both transform template display values, chainable with |.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.