Angular provides several built-in pipes to format data:
uppercase
& lowercase
– Converts text to upper/lower case.date
– Formats dates ({{ today | date:'short' }}
).currency
– Formats numbers as currency.percent
– Converts numbers into percentage format.json
– Converts an object to JSON format.You can apply a built-in pipe in your HTML file like this:
<p>{{ 'hello world' | uppercase }}</p> <!-- Outputs: HELLO WORLD -->
<p>{{ 1000 | currency:'USD' }}</p> <!-- Outputs: $1,000.00 -->
ng generate pipe capitalize
Modify the capitalize.pipe.ts
file:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'capitalize'
})
export class CapitalizePipe implements PipeTransform {
transform(value: string): string {
return value.replace(/\b\w/g, char => char.toUpperCase());
}
}
app.module.ts
Import and declare the pipe in your module:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CapitalizePipe } from './capitalize.pipe';
@NgModule({
declarations: [
CapitalizePipe
],
imports: [
BrowserModule
],
bootstrap: []
})
export class AppModule { }
Now, you can use the capitalize
pipe in your HTML:
<p>{{ 'angular custom pipe example' | capitalize }}</p>
<!-- Outputs: Angular Custom Pipe Example -->
Angular pipes are an essential feature for transforming data efficiently. Built-in pipes make it easy to format text, numbers, and dates, while custom pipes offer more flexibility. By following this guide, you have learned how to create and use a custom pipe in an Angular application. Mastering pipes will help improve the readability and maintainability of your Angular projects. 🚀