Orderby with *ngFor array

C. Banzet picture C. Banzet · Jan 23, 2018 · Viewed 39.1k times · Source

I made the following structure in my json file with Firebase Real Time Database to work on Composer and his Compositions:

enter image description here

I have the following service that give me the data of one composer with his composition

getComposerWithKey(key: string): Observable<Composer> {
const memberPath = `composer/${key}`;
this.composer = this.db.object(memberPath)
  .snapshotChanges().map(action => {
    const $key = action.payload.key;
    const arrcompositions = action.payload.val().compositions?Object.entries(action.payload.val().compositions):null;
    const data = { 
      $key,
      arrcompositions,
      ...action.payload.val() };
    return data;
  });
return this.composer
}

Now I can get the composer info with a list of his compositions with the ngFor directive :

<mat-list-item *ngFor="let composition of composer.arrcompositions">
    {{ composition[1] }}
</mat-list-item>

My problem is that I can't order the compositions in alphabetic order. I tried to use the ngx-order-pipe but I don't know how to precise the value used to order

<mat-list-item *ngFor="let composition of composer.arrcompositions | orderBy: 'composition[1]'">
{{ composition[1] }}

This obviously doesn't work...

Answer

user4676340 picture user4676340 · Jan 23, 2018

You should not use ordering pipes.

The Angular team and many experienced Angular developers strongly recommend moving to filter and sorting logic into the component.

If you want to sort your items by, let's say, name, here it goes :

sortBy(prop: string) {
  return this.composer.arrcompositions.sort((a, b) => a[prop] > b[prop] ? 1 : a[prop] === b[prop] ? 0 : -1);
}

In your HTML :

<mat-list-item *ngFor="let composition of sortBy('name')">
  {{ composition[1] }}
</mat-list-item>