Creating custom dateago Pipe in Angular

In this simple article I am going to demonstrate use of custom pipe in angular that displays given date into date ago format.

What really are pipes in Angular?

Well according to angular.io pipe are nothing but functions you can use in template expressions to accept an input value and return a transformed value.

Here,I am particular interested in usage of date pipe and angular provide some handy date pipes,some of them are,

{{date | date:’mediumDate’}}

{{date | date:’short’}}

{{date | date:’long’}}

{{date | date:’full’}}

{{date | date:’shortDate’}}.

To demonstrate use of pipes provided by angular let’s write some code.

Create a simple Employee Model class.

Next step is to create a employee-list component that initialises list of employee and displayes it.

employee-list.component.ts

Now,lets display these list of employee using below HTML.

employee-list.component.html

Above HTML code snippet shows the use of pipe provided by angular itself.we can provide date format as we needed(the date type are specific to that provided by angular).

This implementation of date pipe gives below view on the browser.

employee-list

In the above UI we are concerned in Hired Date of employee.We have implementated angular date pipe with format ‘mediumDate’,so it displays something like Dec,20,2020.

But,What if we need to display hired date of employee in days ago,months ago,years ago format?Does angular provide date pipe to display in these format?

NO,angular doesn’t provide date pipe to display date in like days ago,months ago,years ago format.Here is how our custom date pipe comes into action.To display date in those format we need to add some external libraries,but we are not going to add external libraries for those works that we can implement ourself.It would be more flexible,customized and testable.

Please add following Date Pipe that i have created.

After creating our Customize date pipe,do not forget to register it into app.module.ts as follow

Let’s impleted out custom dateAgo pipe in HTML snippet.

Output after implemantation of custom pipe

So,here we have successfully displayed date format as we have wished.The benefit of creating custom pipe are that it will be flexible for our use,modification is easy and testability of code can be improved.

So,this was my simple illustration on the use of custom pipe in angular,if you liked it please hit some claps so that i would be motivated to create some other contents.

CHEERS !!!!!!!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store