exhtml
5/30/2018 - 1:34 PM

(RAW) Angular 2 custom pipe filter / sort

sort() {
    this.servers.sort((a: any, b: any) => {
      return b.space - a.space;
    });
  }
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sortwithName'
})
export class SortPipe implements PipeTransform {

  transform(array: any[], field: string): any[] {
    array.sort((a: any, b: any) => {
      if (!a.last.localeCompare(b.last)) 
      {
        return a.first.localeCompare(b.first);
      }
      return a.last.localeCompare(b.last);
    });
    return array;
  }

}

// generate the filter
// ng generate pipe filter


@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(value: any, filterString: string, propName: string): any { //value will be here our array of elements, doesn't have to be a string. 'filterString' es el valor por el que queremos filtrar, 'propName' la propiedad que queremos filtrar
    if (value.length === 0 || filterString === '') { // si no introducimos ninguna cadena de busqueda
      return value;
    }
    return value.filter(item => item[propName] === filterString ); //only return the elements in the array whose property we are filtering fullfill this filterString
  }
}

// In our component:
filteredStatus = '';
// Now in our template create a field two-way databinding to our property, 
// that allows the user to filter our list:
<input type="text" [(ngModel)]="filteredStatus">
//
// we can apply it in ngFor directly:
<li *ngFor="let server of servers | filter:filteredStatus:'status'">