angular keyvalue pipe sort properties / iterate in order

前端 未结 11 946
有刺的猬
有刺的猬 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:24

    According to the Angular documentation, the keyvalue pipe sorts the items by key order by default. You can provide a comparer function to change that order, and sort the items according to the key, to the value, or to the entry order of the properties in the object.

    The following comparer functions sort the items in various orders:

    // Preserve original property order
    originalOrder = (a: KeyValue, b: KeyValue): number => {
      return 0;
    }
    
    // Order by ascending property value
    valueAscOrder = (a: KeyValue, b: KeyValue): number => {
      return a.value.localeCompare(b.value);
    }
    
    // Order by descending property key
    keyDescOrder = (a: KeyValue, b: KeyValue): number => {
      return a.key > b.key ? -1 : (b.key > a.key ? 1 : 0);
    }
    

    when applied to the keyvalue pipe:

    {{item.key}} : {{item.value}}
    {{item.key}} : {{item.value}}
    {{item.key}} : {{item.value}}

    See this stackblitz for a demo.


    Supplying a constant or null instead of a valid comparer function preserves the entry order of the object properties, like originalOrder does, but it causes an exception (see this stackblitz):

    
    
    ERROR TypeError: The comparison function must be either a function or undefined

    Moreover, using that syntax twice in the template does not display the items at all. Therefore, I would not recommend it. Please note that supplying undefined as the comparer function does not cause any exception but does not change the default behavior: the items are sorted by key value.

提交回复
热议问题