I'm trying to create a component where you can pass which pipe that should be used for a list inside the component. From what I could find by testing and looking around for answers the only solution appears to create something like:
<my-component myFilter="sortByProperty"></my-component>
my-component
template:
<li *ngFor="#item of list | getPipe:myFilter"></li>
Which then maps myFilter
to the correct pipe logic and runs it, but this seems a bit dirty and not optimal.
I thought they would have come up with a better solution to this problem since Angular 1 where you would also do something along these lines.
Is there not a better way to do this in Angular 2?
I managed to get something working, it's a bit dirty and evil (with eval) but it does the trick for me. In my case, I have a table component with different data types in each row (e.g title, url, date, status). In my database, status is marked as either
1
asenabled
or0
fordisabled
. Of course, it is more preferable to be showing enabled/disabled to my user. Also, my title column is multilingual, which makes it an object with eitheren
orid
as it's key.Ideally, I need 2 different pipes to convert my data to show to my app's user. Something like
translateTitle
andgetStatus
will do fine. Let's call the parent's pipedynamicPipe
.I'll probably get a lot of hate on using eval. Hope it helps!
Update: when you might need it
Will return:
Building on borislemke's answer, here's a solution which does not need
eval()
and which I find rather clean:dynamic.pipe.ts:
app.module.ts:
app.component.ts:
The easiest way to tackle this would be to not use the pipes in the HTML templates, but instead, inject the pipe into a component's constructor (using DI), then apply the transform functionally. This works quite well with an Observable map or similar rxjs streams.
Unfortunately I don't think so. It's the same as in angular1 where you have a function return a string for the dynamic Pipe you want.
Looking at the docs that's exactly how they show it as well.
https://angular.io/docs/ts/latest/guide/pipes.html
Then in the controller:
Alas, it could be worse! :)