I have a TODOs list, (Todo[ ]) and I want to sort it every time I make
You need to change your html template so that your pipe can accommodate your async code.
Change this line:
<li *ngFor="#todo of todos | sort; #i=index">
(...)
</li>
To this:
<li *ngFor="#todo of todos | async | sort; #i=index">
(...)
</li>
I copied your Pipe code into this Plunker:
https://plnkr.co/edit/RBpZilgxIyRDLwktNZN1?p=preview
Perhaps the value todos
is null
at the beginning because it's loaded asynchronously using HTTP.
To prevent from such use case you could add this in your pipe:
@Pipe({
name: "sort"
})
export class TodosSortPipe implements PipeTransform {
transform(array: Todo[], args: any): Todo[] {
if (array == null) {
return null;
}
(...)
}
}
Then the value todos
will be received and the transform
method of the pipe will be called again with this non null value...
Moreover it seems that your <li>
tag isn't ended. You must have valid HTML into component templates. I don't know if it's the complete code or a truncated one...
Hope it helps you, Thierry
I've created an OrderBy pipe that supports both single and multi-dimensional arrays. It also supports being able to sort on multiple columns of the multi-dimensional array.
<li *ngFor="#todo of todos | orderBy : ['completed']; #i=index">
{{i}}) {{todo.name}} - {{todo.completed}}
</li>
This pipe does allow for adding more items to the array after rendering the page, and still sort the arrays with the new items dynamically.
I have a write up on the process here.
And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info