In this guide let us learn how to use Angular Pipes in components & Services. We usually use Angular Pipes in the template. But a pipe is nothing but a class with a method transform. Whether it is a built-in pipe or custom pipe, we can easily use it in an angular component or service.
Using pipes in your code involves three simple steps
First import the DatePipe from @angular/common. Add it in the Angular Provider metadata providers: [ DatePipe ],.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { DatePipe } from '@angular/common';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [
DatePipe
],
bootstrap: [AppComponent]
})
export class AppModule { }
Open the app.component.html and inject the DatePipe in the constructor.
constructor(private datePipe:DatePipe) {
}
You can use it in component as shown below.
this.toDate = this.datePipe.transform(new Date());
The transform method accepts the date as the first argument. You can supply additional Parameters to DatePipe like format,timezone & locale.
this.toDate = this.datePipe.transform(new Date(),'dd/MM/yy HH:mm');
The complete component code is as below.
import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
selector: 'app-root',
template: `
{{toDate}}
`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'pipesInService';
toDate
constructor(private datePipe:DatePipe) {
}
ngOnInit() {
this.toDate = this.datePipe.transform(new Date());
}
}