What Are Pipes in Angular: Simple Explanation and Examples
pipes are simple functions that transform data before displaying it in the template. They let you format values like dates, numbers, or text easily without changing the original data. You use pipes by adding the pipe symbol | in your template expressions.How It Works
Think of pipes in Angular like kitchen tools that prepare your food before you eat it. Just as you might slice or season vegetables before cooking, pipes take raw data and transform it into a format that is easier to understand or looks nicer on the screen.
When you write a template in Angular, you often want to show data in a specific way, such as showing a date in a readable format or turning text into uppercase. Pipes do this by taking the original data and returning a new, formatted version without changing the original value. This keeps your data clean and your templates simple.
Using pipes is like applying a filter on a photo app: you don’t change the original photo, but you see a nicer version. In Angular, you add pipes by using the | symbol followed by the pipe name right inside your HTML template.
Example
This example shows how to use the built-in date pipe to format a date and the uppercase pipe to change text to uppercase in an Angular template.
import { Component } from '@angular/core'; @Component({ selector: 'app-pipe-example', template: ` <p>Original date: {{ today }}</p> <p>Formatted date: {{ today | date:'fullDate' }}</p> <p>Original text: {{ message }}</p> <p>Uppercase text: {{ message | uppercase }}</p> ` }) export class PipeExampleComponent { today = new Date(); message = 'hello angular pipes'; }
When to Use
Use pipes whenever you want to display data in a different format without changing the original data source. Pipes are perfect for formatting dates, numbers, currencies, percentages, or text transformations like uppercase or lowercase.
For example, if you have a list of product prices, you can use the currency pipe to show them with a currency symbol. If you want to show a user's birthday in a friendly format, the date pipe is ideal. Pipes keep your templates clean and your code easy to maintain.
Key Points
- Pipes transform data in Angular templates without changing the original data.
- Use the pipe symbol
|followed by the pipe name in templates. - Angular provides many built-in pipes like
date,uppercase,currency, and more. - You can create custom pipes for special formatting needs.
- Pipes help keep your templates simple and your data clean.