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.
Table of Contents
Using Pipes in Components & Services
Using pipes in your code involves three simple steps
- Import the pipe in Module
- Inject pipe in the constructor
- Use the transform method of the pipe
Using Date pipe in Components & Services
First import the DatePipe
from @angular/common
. Add it in the Angular Provider metadata providers: [ DatePipe ],
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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.
1 2 3 4 | constructor(private datePipe:DatePipe) { } |
You can use it in component as shown below.
1 2 3 | 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
.
1 2 3 | this.toDate = this.datePipe.transform(new Date(),'dd/MM/yy HH:mm'); |
The complete component code is as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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()); } } |
This article is get information thank you