0

For my Angular project, I want to display the EmpID values in a combo box and have them sorted by the last name.

Here's an html snippet where I'm trying to implement the pipe.

    <select id="empName" [(ngModel)]="selectedEmployee">
      <option selected="selected" disabled>Employee Name...</option>
      <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{emp.EmpID | orderByLast}}</option>
    </select>

and here's my orderByLast.pipe.ts :

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

@Pipe({ name: 'orderByLast' })

export class OrderByLast implements PipeTransform {
    transform(array: Array<string>): Array<string> {
        array.sort((a: any, b: any) => {
            if (a < b) {
                return -1;
            }
            else if (a > b) {
                return 1;
            }
            else {
                return 0;
            }
        });
        return array;
    }
}

and here's my emp-info.ts array:

export class EmpInfo {
    EmpKey: number;
    EmpID: string;
    Firstname: string;
    LastName: string;
    EmpStat: string;
    StartDate: Date;
    AdjustedStart: Date;
    Anniversary: number;
    PTOYear: number;
    STDLTD: number;
    Uncharged: number;
    ETOEarned: number;
    ETORequests: number;
    ETORemaining: number;
    PTOBase: number;
    PTOCarry: number;
    PTOBorrowed: number;
    PTOBalance: number;
    PTORequests: number;
    PTORemaining: number;
}
rcarcia02
  • 927
  • 4
  • 15
  • 46

2 Answers2

1

You need to implement a transform function:

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

@Pipe({ name: 'orderByLast' })

export class OrderByLast implements PipeTransform {
  transform() { // add your object as a parameter to transform()
    //write your code to do the sort
  }
}

See the 'Custom Pipes' section here: https://angular.io/docs/ts/latest/guide/pipes.html (Please note that as @torazaburo pointed it out it's not recommended to do sorts using pipes which is also explained in the link under the 'Appendix: No FilterPipe or OrderByPipe' section.)

Tamas
  • 10,953
  • 13
  • 47
  • 77
  • It's odd that you would cite a reference which recommends **against** doing sorting with pipes (see https://angular.io/docs/ts/latest/guide/pipes.html#!#appendix-no-filterpipe-or-orderbypipe-). –  Jun 05 '17 at 14:49
  • You pointed this out to the person asking as well - it's up to them whether they'll go and read this and adhere to it, or not. Let me do a quick update to my post. – Tamas Jun 05 '17 at 14:50
  • @torazaburo I've updated by post with the code that i put in orderbylast.pipe.ts and it's just printing out a blank combo box. what would I do differently? – rcarcia02 Jun 05 '17 at 15:16
1

See this example. I implemented this orderBy pipe few months ago in my own app. https://stackoverflow.com/a/39650432/5556177

Nehal
  • 13,130
  • 4
  • 43
  • 59