Search code examples
javascriptangularsortingngfor

How do you move table row to the top in Angular ngFor loop?


Using Angular 9, I'm looping through a list of data, but if a value equals primary I want to place that specific row at the top of the list or first.

I have the table working already and I'm looping using *ngFor="let item of items | sort: sortColumn: sortAscending. However, I'm struggling on the front-end to find the primary using item.primary = true and make it first in the loop, and then continue looping.

My Angular skills are limited here. I've seen the answer that unshift() will work, but I'm not sure how to code that into *ngFor.

NOTE: This is the standard <table/> table, not using <mat-table/>.

Hopefully, that makes sense. Thanks!


Solution

  • You can create a pipe that make your element be at the start of the array.
    First you create your pipe:

    import { Pipe, PipeTransform } from "@angular/core";
    @Pipe({ name: "primary" })
    export class PrimaryPipe implements PipeTransform {
      transform(value: any[]): any[] {
        // get index of primary element
        const index = value.findIndex(el => el.primary);
        // get the element itself
        const primaryElement = value[index];
        // remove the element from the array
        value.splice(index, 1);
        // put the element at the start of the array
        value.unshift(primaryElement);
        / return the new arrary
        return value;
      }
    }
    

    Add your new pipe to app module in the declarations.
    Now you can use this pipe in your component:

    *ngFor="let item of items | sort: sortColumn: sortAscending | primary
    

    Here is a live demo to help you out: link
    In the live demo look at the following files:

    • primary.pipe.ts
    • primary-pipe.component.ts

    Check the bottom of the html page for the preview