Sono riuscito a far funzionare qualcosa, è un po 'sporco e malvagio (con eval) ma fa il trucco per me. Nel mio caso, ho un componente tabella con diversi tipi di dati in ogni riga (ad esempio titolo, url, data, stato). Nel mio database, lo stato è contrassegnato come 1
come enabled
o 0
per disabled
. Certo, è più preferibile mostrare la funzione abilitata/disabilitata al mio utente. Inoltre, la mia colonna del titolo è multilingue, il che la rende un oggetto con en
o id
come chiave.
// Example row object:
title: {
"en": "Some title in English",
"id": "Some title in Indonesian"
},
status: 1 // either 1 or 0
Idealmente, ho bisogno di 2 tubi diversi per convertire i miei dati per mostrare all'utente di mia app. Qualcosa come translateTitle
e getStatus
andrà bene. Chiamiamo la pipe del genitore 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]
}
}
Probabilmente otterrò molto odio nell'utilizzare eval. Spero che sia d'aiuto!
Aggiornamento: quando si potrebbe averne bisogno
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>
tornerà:
| title | url | date | status |
| Some post t... a-beautiful... an hour ago enabled
| Some post ...2 a-beautifu...2 2 days ago disabled
è getpipe il tuo filtro personalizzato? –