https://www.tektutorialshub.com/angular/using-angular-pipes-in-components-or-services/
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 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
BEST ANGULAR BOOKS
The Top 8 Best Angular Books, which helps you to get started with Angular
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());
}
}
|
References
'Angular JS' 카테고리의 다른 글
Angular Pass data to child component (0) | 2022.01.15 |
---|---|
Angular Component Communication & Sharing Data (0) | 2022.01.15 |
Angular KeyValue Pipe (0) | 2022.01.15 |
Using Angular Async Pipe with ngIf & ngFor (0) | 2022.01.15 |
Formatting Dates with Angular Date Pipe (0) | 2022.01.15 |
댓글