When working with Angular you may need to do a logic that already exists in a pipe. This tutorial will show how to use pipe in services and components in Angular.
Let’s say we want to use Angular DatePipe.
Declare pipe in Module providers
To take benefit of dependency injection, you need to add the pipe to providers of your Angular module.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [ DatePipe ], bootstrap: [AppComponent] }) export class AppModule { } |
Use the pipe
You can use the pipe by dependency injection like below.
1 2 3 4 5 6 7 8 9 |
export class AppComponent { constructor(private datePipe: DatePipe) { } transformDate(date): string { return this.datePipe.transform(date, 'yyyy-MM-dd'); } } |
That’s it.