Angular 4 中的升序和降序排序

2023-11-27

为什么排序功能有效:

<th (click)="sort('transaction_date')">Transaction Date <i class="fa" [ngClass]="{'fa-sort': column != 'transaction_date', 'fa-sort-asc': (column == 'transaction_date' && isDesc), 'fa-sort-desc': (column == 'transaction_date' && !isDesc) }" aria-hidden="true"> </i></th>

虽然这个不起作用:

<th (click)="sort('user.name')">User <i class="fa" [ngClass]="{'fa-sort': column != 'user.name', 'fa-sort-asc': (column == 'user.name' && isDesc), 'fa-sort-desc': (column == 'user.name' && !isDesc) }" aria-hidden="true"> </i></th>

html

 <tr *ngFor="let inner of order.purchase_orders | orderBy: {property: column, direction: direction}">
        <td>{{ inner.transaction_date | date  }}</td>
        <td>{{ inner.user.name  }}</td>
 </tr>

ts

sort(property){
    this.isDesc = !this.isDesc; //change the direction    
    this.column = property;
    this.direction = this.isDesc ? 1 : -1;
    console.log(property);
  };

pipe

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

@Pipe({
  name: 'orderBy'
})

export class OrderByPipe implements PipeTransform {

  transform(records: Array<any>, args?: any): any {
    if(records && records.length >0 ){
    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;
          }
        });
      }
    };
}

提前致谢。


这里的问题是:

对象的嵌套属性,orderBy 必须提供排序 第一级属性的基础

我正在考虑,inner应该是这样的

{
    transaction_date : '10/12/2014'
    user : {
        name : 'something',
        ...
    }
}

尝试使该对象像在第一级上获取所有可排序属性 (或者你必须改变顺序通过这种方式)

{
    transaction_date : '10/12/2014'
    user_name : 'something',
    user : {
        name : 'something',
        ...
    }
}

And try.

<th (click)="sort('user_name')">
    User <i class="fa" [ngClass]="{'fa-sort': column != 'user_name', 
                                    'fa-sort-asc': (column == 'user_name' && isDesc), 
                                    'fa-sort-desc': (column == 'user_name' && !isDesc) }" 
            aria-hidden="true"> 
        </i>
</th>

Add records.map(record => record['user_name'] = record.user.name);,给你的transform函数,像这样:

这将按照我的建议创建对象:

export class OrderByPipe implements PipeTransform {

  transform(records: Array<any>, args?: any): any {
    if(records && records.length >0 ){

    records.map(record => record['user_name'] = record.user.name); // add here

    return records.sort(function(a, b){
        ....
      }
    };
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 4 中的升序和降序排序 的相关文章

随机推荐