angular keyvalue pipe sort properties / iterate in order

前端 未结 11 945
有刺的猬
有刺的猬 2020-11-29 21:01

When using the Angular keyvalue pipe to iterate over an object\'s properties as follows:

11条回答
  •  醉梦人生
    2020-11-29 21:31

    This is same as accepted answer, but it has more complex object so It can help somebody How to sort by custom index field and using keyval pipe.

    In angular component:

    myObject = {
        "key1": { val:"whateverVal1", code:"whateverCode1", index: 1},
        "key2": { val:"whateverVal2", code:"whateverCode2", index: 0},
        "key3": { val:"whateverVal3", code:"whateverCode3", index: 2}
    }
    

    Sorting function in component:

    indexOrderAsc = (akv: KeyValue, bkv: KeyValue): number => {
            const a = akv.value.index;
            const b = bkv.value.index;
    
            return a > b ? 1 : (b > a ? -1 : 0);
        };
    

    in template:

    ...

提交回复
热议问题