Angular 4使用OrderBy管道不起作用



我正在处理排序列。但是,当我从组件中传递分类变量时,它不起作用。工作场景:

<th>Contact</th>
<ng-container *ngFor="let item of (itemsToShow | orderBy:['-age', 'firstName'])">
</ng-container>

但是,当我尝试以相同方式从组件中设置变量时,代码无法正常工作。组件文件功能:

changeOrderBy() {
 this.orderset = '['-age', 'firstName']';
}

html文件:

<th (click)="changeOrderBy()">Contact</th>
<ng-container *ngFor="let item of (itemsToShow | orderBy:orderset )">
</ng-container>  

请参阅下面的链接以获取参考:

http://embed.plnkr.co/dhlvc0

我记得我使用了这个管道示例,并且由于我遇到的一些错误而不得不更改它。

这是现在的外观:

/*
 * Example use
 *      Basic Array of single type: *ngFor="let todo of todoService.todos | orderBy : '-'"
 *      Multidimensional Array Sort on single column: *ngFor="let todo of todoService.todos | orderBy : ['-status']"
 *      Multidimensional Array Sort on multiple columns: *ngFor="let todo of todoService.todos | orderBy : ['status', '-title']"
 */
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'orderBy', pure: false })
export class OrderBy implements PipeTransform {
    value: string[] = [];
    static _orderByComparator(a: any, b: any): number {
        if (a === null || typeof a === 'undefined') { a = 0; };
        if (b === null || typeof b === 'undefined') { b = 0; };
        if (typeof a === 'string') { a = a.toLowerCase(); }
        if (typeof b === 'string') { b = b.toLowerCase(); }
        if ((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))) {
            // Isn't a number so lowercase the string to properly compare
            if (a + ''.toLowerCase() < b + ''.toLowerCase()) { return -1; }
            if (a + ''.toLowerCase() > b + ''.toLowerCase()) { return 1; }
        } else {
            // Parse strings as numbers to compare properly
            if (parseFloat(a) < parseFloat(b)) { return -1; }
            if (parseFloat(a) > parseFloat(b)) { return 1; }
        }
        return 0; // equal each other
    }
    transform(input: any, config: string = '+'): any {
        // make a copy of the input's reference
        this.value = [...input];
        let value = this.value;
        if (!Array.isArray(value)) { return value; }
        if (!Array.isArray(config) || (Array.isArray(config) && config.length === 1)) {
            let propertyToCheck: string = !Array.isArray(config) ? config : config[0];
            let desc = propertyToCheck.toString().substr(0, 1) === '-';
            // Basic array
            if (!propertyToCheck || propertyToCheck === '-' || propertyToCheck === '+') {
                return !desc ? value.sort() : value.sort().reverse();
            } else {
                let property: string = propertyToCheck.toString().substr(0, 1) === '+' || propertyToCheck.toString().substr(0, 1) === '-'
                    ? propertyToCheck.toString().substr(1)
                    : propertyToCheck;
                return value.sort(function (a: any, b: any) {
                    return !desc
                        ? OrderBy._orderByComparator(a[property], b[property])
                        : -OrderBy._orderByComparator(a[property], b[property]);
                });
            }
        } else {
            // Loop over property of the array in order and sort
            return value.sort(function (a: any, b: any) {
                for (let i: number = 0; i < config.length; i++) {
                    let desc = config[i].substr(0, 1) === '-';
                    let property = config[i].substr(0, 1) === '+' || config[i].substr(0, 1) === '-'
                        ? config[i].substr(1)
                        : config[i];
                    let comparison = !desc
                        ? OrderBy._orderByComparator(a[property], b[property])
                        : -OrderBy._orderByComparator(a[property], b[property]);
                    // Don't return 0 yet in case of needing to sort by next property
                    if (comparison !== 0) { return comparison; }
                }
                return 0; // equal each other
            });
        }
    }
}

我不确定更改管道的论点要求重新评估该管道的结果。

您是否尝试使用组件中的功能?您可以将一个值数组作为组件的属性和组件中的方法,这些属性根据您的标准对数组进行排序。

@Component( ... )
export class YourComponent {
  itemsToShow: Contact[];
  changeOrderBy() {
    SortUtils.sortArrayBy(this.itemsToShow, ['-age', 'firstName']);
  }
}
export class SortUtils {
  static sortArrayBy(array: any[], args: string[]) {
    // Your sort logic here...
    // You may copy/paste the code from the library
    // But I recommend rewrite the logic entirely instead.
  }
}

最新更新