Eladerezador
Eladerezador

Reputation: 1301

Angular 4 - Sort Column Table

I have based on this example to sort the columns of a table: Sort Table Colums

This is the code pipe:

import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({  name: 'orderBy' })
export class OrderrByPipe implements PipeTransform {

  transform(records: Array<any>, args?: any): any {

    return records.sort(function(a, b){
          if(a[args.property] < b[args.property]){
            return -1 * args.direction;
          }
          else if( a[args.property] > b[args.property]){
            return 1 * args.direction;
          }
          else{
            return 0;
          }
        });
    };
}

This is the html code:

<tr *ngFor="let particular of particulars | orderBy: {property: column, direction: direction} | slice:1; let i = index">

The import in the component:

import { OrderrByPipe } from '../pipes/orderby.pipe';

I want to migrate the pipe class to Angular 4, How could do it?

This is the error in console:

error_handler.js:60 Error: Uncaught (in promise): Error: Error in ./ParticularsListComponent class ParticularsListComponent - inline template:42:14 caused by: Cannot read property 'sort' of undefined
Error: Error in ./ParticularsListComponent class ParticularsListComponent - inline template:42:14 caused by: Cannot read property 'sort' of undefined

Upvotes: 1

Views: 8911

Answers (2)

chaithu kumar
chaithu kumar

Reputation: 1

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

@Pipe({
  name: 'orderby'
})
export class OrderbyPipe implements PipeTransform {


  //private records : Array<any> = [];

    transform(records :Array<Object>, args?: any): any {
    if(records != null){
      return records.sort(function(a, b){
            if (a[args.property] === '' || a[args.property] === null || typeof a[args.property] === 'undefined') {
            return 1 * args.direction;
            }
            if (b[args.property] === '' || b[args.property] === null || typeof b[args.property] === 'undefined') {
            return -1 * args.direction;
            }
          if(a[args.property] < b[args.property]){
            return -1 * args.direction;
          }
          else if( a[args.property] > b[args.property]){
            return 1 * args.direction;
          }
          else{
            return 0;
          }
        });
    }
    };

}

Upvotes: 0

user4676340
user4676340

Reputation:

Your problem comes from the particulars variable that is undefined.

Upvotes: 2

Related Questions