Ericky
Ericky

Reputation: 664

How to display certain items first in Angular *ngFor

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.

Upvotes: 0

Views: 952

Answers (1)

SplitterAlex
SplitterAlex

Reputation: 2823

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.

Upvotes: 2

Related Questions