Using Pipes in a Component Class in Angular

Using Pipes in a Component Class in Angular

Angular pipes provide an easy way to transform your output within your HTML template before displaying to the user. However, while building an Angular application it is very likely that you will face a situation where you want to use the pipe within your component class. In this tutorial, we will learn to utilize pipe feature to format values within our component class.

Recommended Post: Different Ways To Use NgClass

Now, let’s say that you wish to use the default date pipe within the component class to transform the date. You can simply do that by injecting your pipe inside the component class.

import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
  selector: 'app-user-profile',
  templateUrl: `user-profile.component.html',
  providers: [DatePipe]
}) 
export class UserProfileComponent {
 
  dateOfBirth = new Date(1988, 10, 31); // October 31, 1988
  constructor(private date: DatePipe) { }

  formatDate() {
    return this.date.transform(this.dateOfBirth, 'yyyy-mm-dd');
  }
}

As you can see from the above code, we are importing the DatePipe from @angular/common.

import { DatePipe } from '@angular/common';

Then we have added the DatePipe to providers array of component (alternately, you can also add it to module’s provider array)

providers: [DatePipe]

Then, we have injected the DatePipe through the constructor of the component.

constructor(private date: DatePipe) { }

And at the end, we are using transform method to format the date.

this.date.transform(this.dateOfBirth, 'yyyy-mm-dd');

That’s it. You can also use your own custom pipes inside the component classes in a similar manner.

For more information: https://angular.io/guide/pipes

Leave a Reply

Your email address will not be published. Required fields are marked *