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
as enabled
or 0
for disabled
. 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 either en
or id
as it's key.
// Example row object:
title: {
"en": "Some title in English",
"id": "Some title in Indonesian"
},
status: 1 // either 1 or 0
Ideally, I need 2 different pipes to convert my data to show to my app's user. Something like translateTitle
and getStatus
will do fine. Let's call the parent's pipe dynamicPipe
.
/// some-view.html
{{ title | dynamicPipe:'translateTitle' }}
{{ status | dynamicPipe:'getStatus' }}
/// dynamic.pipe.ts
//...import Pipe and PipeTransform
@Pipe({name:'dynamicPipe'})
export class DynamicPipe implements PipeTransform {
transform(value:string, modifier:string) {
if (!modifier) return value;
return eval('this.' + modifier + '(' + value + ')')
}
getStatus(value:string|number):string {
return value ? 'enabled' : 'disabled'
}
translateTitle(value:TitleObject):string {
// defaultSystemLanguage is set to English by default
return value[defaultSystemLanguage]
}
}
I'll probably get a lot of hate on using eval. Hope it helps!
Update: when you might need it
posts = {
content: [
{
title:
{
en: "Some post title in English",
es: "Some post title in Spanish"
},
url: "a-beautiful-post",
created_at: "2016-05-15 12:21:38",
status: 1
},
{
title:
{
en: "Some post title in English 2",
es: "Some post title in Spanish 2"
},
url: "a-beautiful-post-2",
created_at: "2016-05-13 17:53:08",
status: 0
}
],
pipes: ['translateTitle', null, 'humanizeDate', 'getStatus']
}
<table>
<tr *ngFor="let row in posts">
<td *ngFor="let column in row; let i = index">{{ column | dynamicPipe:pipes[i] }}</td>
</tr>
</table>
Will return:
| title | url | date | status |
| Some post t... a-beautiful... an hour ago enabled
| Some post ...2 a-beautifu...2 2 days ago disabled