1

I'm trying to create a live scoreboard for a game where I'm feeding my app with a logfile.

I'm using

public players = {}; // <string, Player>

To contain a list of players where the string is the key. play.model.ts looks like this:

export class Player {
  public name: string;
  public kills: number;
  public deaths: number;

  constructor(name: string) {
    this.name = name;
    this.kills = 0;
    this.deaths = 0;
  }
}

So my view looks like this

      <tr *ngFor="let player of scoreboardService.players | keyvalue: sortByKills">
        <td>{{ player.value.name }}</td>
        <td>{{ player.value.kills }}</td>
        <td>{{ player.value.deaths }}</td>
      </tr>

and here I'm using keyvalue with the comparator function sortByKills()

  sortByKills = (p1: KeyValue<string, Player>, p2: KeyValue<string, Player>): number => {
    return p2.value.kills - p1.value.kills;
  }

The table updates correctly, however the sorting is not applied. Any suggestions?

1 Answers1

1

Look at example I put in Demo with custom pipe

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'keyvalue'
})

export class CustomPipe implements PipeTransform {
  transform(row: any[],sortByKills:number=-1): any {
      // make your filters here 
      return row.sort((a, b) => sortByKills*(parseFloat(a.kills) - parseFloat(b.kills)));

  }
}
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54