Custom Pipes
Angular already gives you useful built-in pipes to format data, like
This is where custom pipes come in
Custom pipes let you
Example: Creating a Custom Pipe to Square a Number
Step 1: Create a New Angular Project
- Date formatting
- Uppercase/lowercase text
- Currency formatting
This is where custom pipes come in
Custom pipes let you
- Write your own logic
- Transform data exactly the way you want
- Keep your templates clean and reusable
Example: Creating a Custom Pipe to Square a Number
Step 1: Create a New Angular Project
ng new Angular
Step 2: Generate a Custom Pipe
ng g pipe pipes/custom-pipes
This creates two files
- custom-pipes.pipe.ts
- custom-pipes.pipe.spec.ts (for testing)
Step 3: Add Logic to Your Custom Pipe
Edit custom-pipes.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'square'})export class CustomPipesPipe implements PipeTransform { transform(value: number): number { return value * value; }}
Here is what this does:
Step 4: Add Data to Use the Pipe
Edit app.component.ts
- @Pipe({ name: 'square' }) - The pipe will be used as | square in templates
- transform method - Takes the input number and returns its square
Step 4: Add Data to Use the Pipe
Edit app.component.ts
import { Component } from '@angular/core';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'Angular'; originalNumber = 5;}
Step 5: Use the Custom Pipe in Your Template
Edit app.component.html
<h1>Custom Pipes Example</h1><div> Original Number: {{ originalNumber }}</div><div> Squared Number: {{ originalNumber | square }}</div>
| square applies the custom pipe you created.
Step 6: Run Your App
ng serve
Open your browser at:
http://localhost:4200
You will see
Original Number: 5Squared Number: 25