In AngularJS, I am able to use filters (pipes) inside of services and controllers using syntax similar to this:
$filter('date')(myDate, 'yyyy-MM-dd');
Is it possible to use pipes in services/components like this in Angular?
You don't have to duplicate your code if you want to also use a pipe's functionality in a component class. All you have to do really is inject the pipe like a service, and then call its transform method. The following works for any Angular 2+ app.
Yes, it is possible by using a simple custom pipe.
I'm going to show you about angular pipe in ts file. Follow bellow tutorial step of how to use angular pipe in component. We will use angular pipe in component file and you can use in angular 6, angular 7, angular 8 and angular 9 application.
Use pipes to transform strings, currency amounts, dates, and other data for display. Pipes are simple functions to use in template expressions to accept an input value and return a transformed value. Pipes are useful because you can use them throughout your application, while only declaring each pipe once.
As usual in Angular, you can rely on dependency injection:
import { DatePipe } from '@angular/common'; class MyService { constructor(private datePipe: DatePipe) {} transformDate(date) { return this.datePipe.transform(date, 'yyyy-MM-dd'); } }
Add DatePipe
to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe
:
providers: [DatePipe,...]
Update Angular 6: Angular 6 now offers pretty much every formatting functions used by the pipes publicly. For example, you can now use the formatDate
function directly.
import { formatDate } from '@angular/common'; class MyService { constructor(@Inject(LOCALE_ID) private locale: string) {} transformDate(date) { return formatDate(date, 'yyyy-MM-dd', this.locale); } }
Before Angular 5: Be warned though that the DatePipe
was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).
If you're using older Angular versions, you should add the Intl
polyfill to your project to avoid any problem. See this related question for a more detailed answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With