0

I have an array with items, one of the fields is 'status' which value can be 'locked' or 'unlocked'.

When I do an *ngFor,

<li *ngFor="let item of items">
  {{item.name}}
</li>

I want items with status 'locked' to be displayed first.

How can I achieve this? Thanks.

Ericky
  • 654
  • 6
  • 15
  • Try this Q&A for sort your array by `status` key : https://stackoverflow.com/questions/8837454/sort-array-of-objects-by-single-key-with-date-value?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Hasan Fathi May 24 '18 at 04:07

1 Answers1

2

You can create a pipe which handles the sorting of your items.

import { Pipe, PipeTransform } from '@angular/core';


@Pipe({name: 'sortItems'})
export class SortItemsPipe implements PipeTransform {
  transform(items: any[]): any[] {
    if (!items) {
      return [];
    }
    
    const sortedItems = items.sort((itemA, itemB) => {
      if (itemA.status === 'locked' && itemB.status === 'unlocked') {
        return 1;
      } else if (itemA.status === 'unlocked' && itemB.status === 'locked') {
        return -1;
      } else {
        return 0;
      }
    })
    
    return sortedItems
    
  }
}

Declare SortItemsPipe in your module and use it like this in your template:

<li *ngFor="let item of items | sortItems">
  {{item.name}}
</li>

For now on all items with status unlocked will come first.

SplitterAlex
  • 2,755
  • 2
  • 20
  • 23
  • Sorting pipes are discouraged by Angular for performance reasons. It's better to sort the array in the component and store the sorted array for display. – Ingo Bürk May 24 '18 at 05:42