I want to order my result by a property name but the following gives me an error:
*ngFor="let s of rslt| order by:wind_park">
what i get from back-end:
data = [
{ turbine_name: "Baynne ", wind_park: "Bayone" },
{ turbine_name: "Salstiegl ", wind_park: "Salzst" },
{ turbine_name: "Chradurga - SLL2", wind_park: "Chiarga" },
{ turbine_name: "Moilishte ", wind_park: "Mogihte" },
{ turbine_name: "Mogshte ", wind_park: "Mogshte" }
]
How can I order it and what's the best practice? Thank you all in advance.
You need to create your own OrderBy pipe to satisfy your needs, lodash is a cool library which has bunch of ready made functions which do the trick orderBy.
import { Pipe, PipeTransform } from "@angular/core";
import { orderBy } from 'lodash';
@Pipe({
name: "orderBy"
})
export class OrderByPipe implements PipeTransform {
transform(array: any, sortBy: string, order?: string): any[] {
const sortOrder = order ? order : 'asc'; // setting default ascending order
return orderBy(array, [sortBy], [sortOrder]);
}
}
Usage in template
<div *ngFor="let w of data | orderBy: 'wind_park'">{{ w.wind_park}}</div> //default will sort ascending
for descending pass the desc in pipe
<div *ngFor="let w of data | orderBy: 'wind_park': 'desc'">{{ w.wind_park}}</div>
Make sure you declare pipe in your module
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ OrderByPipe ], // declare pipe here
bootstrap: [ AppComponent ]
})
Working DEMO
Angular does not provide a pipe for sorting items. You have to implement it yourself. I think the best way to sort items is through a pipe. That is a simple example:
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "sort"
})
export class ArraySortPipe implements PipeTransform {
transform(array: any, field: string): any[] {
if (!Array.isArray(array)) {
return;
}
array.sort((a: any, b: any) => {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
return array;
}
}
To use it:
*ngFor="let value of myArr | sort:'fieldName'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With