The subject
I'm building an abstract table component to which I pass what pipe it should use in certain columns. As the data passed may vary, so the pipes should vary as well.
The goal
To use whatever pipe is passed to the table
The project
Here's how it should look like in html in my opinion
<!-- html -->
<span *ngIf="element.pipe">{{ row[element.column] | <<here_inject_an_appropriate_pipe>> }}</span>
The column settings are passed through an object and have form of
//typescript
columnSettings: [
...
{column: 'fruitExpDate', caption: 'Best before', pipe: 'date: \"' + PIPE_DATE_FORMAT + '\"' },
...
]
and PIPE_DATE_FORMAT
holds the string 'yyyy-MM-dd'
What I tried
- Passing the pipe directly through a variable like
<!-- html -->
<span *ngIf="element.pipe">{{ row[element.column] | element.pipe }}</span>
- Creating custom pipe which takes another pipe as an argument
@Pipe({
name: 'dynamicPipe',
})
export class DynamicPipe implements PipeTransform {
// constructor(private abstractTableService: AbstractTableService) {}
transform(value: any, pipe: string): any {
const pipeToken: any = pipe.split(':')[0].replace(/[\s]+/g, '');
const pipeArgs: any = pipe.split(':')[1].replace(/[\s]+/g, '');
console.log(value);
console.log(pipe);
// return pipeToken.transform(value, ...pipeArgs);
return 'check pipe';
}
}
and here I tried many different things to call the requested pipe but eventually didn't figure out how to do this. Here's my html with the custom pipe:
<!-- html -->
<span *ngIf="element.pipe">{{ row[element.column] | dynamicPipe: element.pipe }}</span>
- Creating a custom service to call imported pipes
@Injectable()
export class AbstractTableService {
constructor(
private date: DatePipe,
) {}
getDatePipe(): DatePipe {
return this.date;
}
}
but here I had no idea how to use this service effectively.