Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a pipe in a component in Angular 2?

I have a pipe class which returns data based on the arguments you are passing. I know how to use it in my template HTML using the | symbol, but I want to use it in my component too.

Is there a way to call a pipe directly from inside a component or a service in Angular 2?

like image 517
Eran Shabi Avatar asked Apr 23 '16 21:04

Eran Shabi


People also ask

Can I use pipe in component angular?

It's easy to create custom pipes to use in your templates to modify interpolated values. 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.

Can I use pipe in TS file?

A pipe is a function or operator that allows us to pass the output of a function as the input of another. JavaScript and TypeScript don't support pipes natively (as an operator), but we can implement our pipes using the following function: const pipe = <T>(...

What is a pipe in Angular 2 +?

These filters are known as "Pipes" in Angular 2. Pipes allow us to change the data inside the template. Normally, a pipe takes the data and transforms this input to the desired output. There are many built-in pipes in Angular 2.


2 Answers

You can call your pipe directly in your code by using:

YourPipeClass.prototype.transform(value, arg1, arg2);

You can call it from inside your component or from anywhere else that imports it.

There is also the new way:

new SortTodosPipe().transform(value, arg1, arg2);

But keep in mind it will create an object, so either save that object for later use or use the prototype method.

Anyway you choose, you must add the pipe to your providers if you use it inside a component, like so:

@NgModule({
    providers: [YourPipe]
})
like image 62
Eran Shabi Avatar answered Sep 28 '22 03:09

Eran Shabi


I would keep the reusable part of what you're trying to do in a separate service, which can then be injected anywhere. This feels like a slippery slope to something less testable and reusable.

like image 20
Fiddles Avatar answered Sep 28 '22 04:09

Fiddles