How to use Angular 8 keyvalue and compareFn with a complex object

Viewed 1673

I have this object

  {
  "id": 1,
  "paragraphText": "I'm some Paragraph Text",
  "paragraphName": "new paragraph",
  "paragraphPlacement": {
    "id": 1,
    "order": 1
  }
}
  {
  "id": 1,
  "paragraphText": "I'm another Paragraph Text",
  "paragraphName": "old paragraph",
  "paragraphPlacement": {
    "id": 1,
    "order": 2
  }
}

I'm trying to sort it by using the keyvalue pipe.

<div class="col-8">
<div *ngFor="let paragraph of offer.offerContent.paragraphs | keyvalue">
{{paragraph.paragraphName}} : {{paragraph.paragraphPlacement.order}}

As I understand it, keyvalue is expecting a key:value map but the angular documentation says you can use comparefn to compare complex objects, however I can't find any documentation or examples of how to use comparefn. So my question is how do I use comparefn to sort my above example on the "paragraphPlacement:order" value.

1 Answers

To achieve expected result, use below option of using key and value pair with compareFn

Issue:
On using keyValue pipe , inside ngFor use paragraph.value to access each object

 <div *ngFor="let paragraph of obj | keyvalue">
    {{paragraph.value.paragraphName}} :
    {{paragraph.value.paragraphPlacement.order}}
    <div>

To sort objects by value, use compare function as below by comparing values and return 1, -1 and 0(incase of comparing equal values)

  sortOrder = (old, nw) => {
        if(old.value.paragraphPlacement.order < nw.value.paragraphPlacement.order){
          return 1
        }else{
          return -1
        }
  }

component.html:

<div *ngFor="let paragraph of obj | **keyvalue** : **sortOrder**">
    {{paragraph.value.paragraphName}} : {{paragraph.value.paragraphPlacement.order}}
    <div>

working code sample
https://codesandbox.io/s/angular-xs3d3

Related