1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

OrderBy pipe in angular 4

Discussão em 'Angular' iniciado por przemlat, Outubro 14, 2024.

  1. przemlat

    przemlat Guest

    I'm trying to write sorting pipe according to code in this link: http://www.advancesharp.com/blog/1211/angular-2-search-and-sort-with-ngfor-repeater-with-example Although I have trouble with dealing with undefined values. My pipe works correctly on columns where there are not any undefined values. But when there is at least one undefined value in column pipe work in a strange way. My code below:

    html template:

    *ngFor="let candidate of filteredList | orderBy:{property: column, direction: direction}"


    in html template to choose column and direction eg:

    <th class="pointer" nowrap="nowrap" (click)="sort('lastName')">{{ 'candidates.candidates' | translate }}
    <i class="fa" [ngClass]="{'fa-sort': column != 'lastName',
    'fa-sort-asc': (column == 'lastName' && !isDesc),
    'fa-sort-desc': (column == 'lastName' && isDesc) }"
    aria-hidden="true"> </i></th>


    order-by.pipe.ts

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

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

    transform(candidates: Array<object>, args?: any): any {
    candidates = candidates || [];
    return candidates.sort(function (a, b) {

    if (a[args.property] === b[args.property]) {
    return 0;
    }
    if (a[args.property] === '' || a[args.property] === null || typeof a[args.property] === 'undefined') {
    return 1;
    }
    if (b[args.property] === '' || b[args.property] === null || typeof b[args.property] === 'undefined') {
    return -1;
    }
    if (a[args.property] < b[args.property]) {
    console.log(a[args.property] + ' wartosc property');
    return -1 * args.direction;
    } else if (a[args.property].toLowerCase() > b[args.property].toLowerCase()) {
    return 1 * args.direction;
    } else {
    return 0;
    }
    });
    }
    }


    component.ts:

    public sort(property: string) {
    this.isDesc = !this.isDesc;
    this.column = property;
    this.direction = this.isDesc ? 1 : -1;
    }


    I was trying many different approaches but none of then was worinkg fine.

    Continue reading...

Compartilhe esta Página