Looping Over An Array Returned By An Imported Function?
We have the async pipe to resolve Observables within template *ngFor expressions. Is there a pipe that can resolve / call a function that returns an array to be looped over. For
Solution 1:
You can simply do
<app-todo *ngFor="let todo of todosFunction()">
and define todosFunction()
, which returns an array, in your ts
file.
Solution 2:
There aren't any built in ones but writing one is pretty simple:
Pipe
@Pipe({
name: 'call'
})
export class CallPipe implements PipeTransform {
transform(value: any, args?: any): any {
if(typeof value === 'function') {
return value(args);
}
}
}
Component.ts
exportclassAppComponent {
data(times) {
return [1, 2, 3].map(x => x*times);
}
}
Component.html
<p *ngFor="let i of data | call: 3">{{i}}</p>
This is a list of built-in pipes if you wonder.
Solution 3:
You can just call the function like this? , there is no need of another pipe to do the same.
<app-todo *ngFor="let todo of todosFunction()">
however it is recommended to prepare your array inside the component and bind it to variable instead of calling a function.
Solution 4:
Call function in template is really bad as function will be executed on each Change Detection cycle.
Pipe in other hand is pure (by default) so it will be called only when input parameters was changed.
@Pipe({
name: 'apply',
})
export classApplyPipeimplementsPipeTransform{
transform<T, U extends any[]>(fn: (...fnArgs: U) => T, ...args: U): T {
returnfn(...args);
}
}
Post a Comment for "Looping Over An Array Returned By An Imported Function?"