To implement a custom pipe that calculates age from a birthdate in Angular:
Step 1: Create the Pipe
ng generate pipe age
Step 2: Implement Logic in Pipe
typescript
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'age' })
export class AgePipe implements PipeTransform {
transform(value: Date | string): number {
const birthDate = new Date(value);
const today = new Date();
let age = today.getFullYear() - birthDate.getFullYear();
const m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
}
Step 3: Use in Template
<p>Age: {{ user.birthdate | age }}</p>