Search This Blog

2023/09/02

How to create custom pipe in angular for age calculation ?


ng g pipe age


in age.pipe.ts add

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
name: 'age'
})
export class AgePipe implements PipeTransform {

transform(value: Date): string {
let today = moment();
let birthdate = moment(value);
let years = today.diff(birthdate, 'years');
let html: string = years + " yr ";

html += today.subtract(years, 'years').diff(birthdate, 'months') + " mo";

return html;

}

}

in app.module.ts

import { AgePipe } from './age.pipe'

add AgePipe to Declartion section

Now you can user it as

{{result.AstroProfileUser.birthtime|age}}

in interpolation

No comments:

Post a Comment