2017-09-17 78 views
0

我有ul列表:如何按值Angular 2排序對象?

<ul> 
<li [ngClass]="{'active': lang.def, 'show': opened}" *ngFor="let lang of languages | orderBy: 'def': 1">{{lang.name}</li> 
</ul> 

我試圖通過價值def排序對象languages。所以,首先應該是li元素與def = 1

我想這pipe過濾器:

export class OrderBy { 

    transform(array: any, orderBy: any, asc = true) { 
    array.sort(function(x: any, y: any) { 
     return (x.def > y.def) ? x.def : y.def; 
    }); 

    return array; 
    } 
} 

但它不爲我工作。

JSON對象:

的所有
[ { "id": 2, "code": "ru", "active": true, "def": 0, "hide": false }, { "id": 1, "code": "az", "active": true, "def": 1, "hide": false } ] 
+0

你能解釋一下使用示例json數據嗎?此外,請參閱[**本文**](https://stackoverflow.com/questions/45267001/how-to-filter-ngfor-result-based-on-a-selected-dropdown-value/45267033#45267033) – Aravind

+0

對不起,我忘了發佈JSON對象,再次看到 – OPV

+0

我需要'def = 1'的那個元素將會是第一個 – OPV

回答

0

首先不是你如何使用管道,其次你的函數是錯誤的。這裏是解決方案

export class OrderBy implements PipeTransform { 
    transform(array: any, orderBy: any, asc = true) { 
    array.sort(function(x: any, y: any) { 
     return x.def - y.def; 
    }); 

    return array; 
    } 
    }