How To Use Angular Pipes In Components OR Services

How To Use Angular Pipes In Components OR Services

In this article, we will learn about the how to use Angular Pipes in components and services. In the template, we commonly use Angular Pipes. A pipe, on the other hand, is nothing more than a class with a convert method. We can easily use it in an angular component or service, whether it's a built-in pipe or a custom pipe.

Using Pipes in Components & Services

There are three basic steps to using pipes in your code.

  • In Module, import the pipe.
  • Pipe should be injected into the constructor.
  • Use the pipe's transform technique.

Components & Services: Using Date Pipe

Import the DatePipe from @angular/common and 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 { }

Now, open the app.component.html and Inject the DatePipe in the function.
constructor(private datePipe:DatePipe) {
}

It's possible to use it in a component, as like below.
this.toDate = this.datePipe.transform(new Date());

The date is the first argument to the transform method. DatePipe accepts extra parameters such as format, timezone and locale.
this.toDate = this.datePipe.transform(new Date(),'dd/MM/yy HH:mm');

The final code of app.component.ts can be found 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());
  }
}


Conclusion

In this article, we learned about the how to use Angular Pipes in components and services. In next article we learn about the component communication.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post