Angular JS

Using Angular Pipes in Components or Services

황기하 2022. 1. 15.

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.

 

Introduction to Angular Services - TekTutorialsHub

This Angular Services tutorial shows you how to create a component that fetches the list of products from an Angular Service and displays it

www.tektutorialshub.com

Using Pipes in Components & Services

Using pipes in your code involves three simple steps

  1. Import the pipe in Module
  2. Inject pipe in the constructor
  3. 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

  1. Transforming Data Using Pipes

댓글