I'm not able to translate this code from angualr1 to angular2, any help?
ng-repeat="todo in todos | orderBy: 'completed'"
This is what i've done following the Thierry Templier's answer:
html template:
*ngFor="#todo of todos | sort"
component file:
@Component({
selector: 'my-app',
templateUrl: "./app/todo-list.component.html",
providers: [TodoService],
pipes: [ TodosSortPipe ]
})
pipe file:
import { Pipe } from "angular2/core";
import {Todo} from './todo';
@Pipe({
name: "sort"
})
export class TodosSortPipe {
transform(array: Array<Todo>, args: string): Array<Todo> {
array.sort((a: any, b: any) => {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return array;
}
}
I'm sure that the error is in the @Pipe, im trying to sort an array of Todos, ordered by the property todo.completed. First todo.completed = false and than the todo.complete = true.
I'm honest, I didn't understand very well the transform method and how to pass the arguments in that method and in the sort method.
Like, what is the args: string argument? a and b, what are they? where they come from?
This is good replacement for AngularJs orderby pipe in angular 4. Easy and simple to use.
This is github URL for more information https://github.com/VadimDez/ngx-order-pipe
Updated OrderByPipe: fixed not sorting strings.
create a OrderByPipe class:
in your controller:
or in your
in your html:
In the current version of Angular2, orderBy and ArraySort pipes are not supported. You need to write/use some custom pipes for this.
You could implement a custom pipe for this that leverages the
sort
method of arrays:And use then this pipe as described below. Don't forget to specify your pipe into the
pipes
attribute of the component:It's a simple sample for arrays with string values but you can have some advanced sorting processing (based on object attributes in the case of object array, based on sorting parameters, ...).
Here is a plunkr for this: https://plnkr.co/edit/WbzqDDOqN1oAhvqMkQRQ?p=preview.
Hope it helps you, Thierry
As we know filter and order by are removed from ANGULAR 2 and we need to write our own, here is a good example on plunker and detailed article
It used both filter as well as orderby, here is the code for order pipe
For Angular 5+ Version we can use ngx-order-pipe package
Source Tutorial Link
Install package
Import in apps module
use anywhere