【问题标题】:Sorting direction and order in Angular table (ascending, descending)Angular 表中的排序方向和顺序(升序、降序)
【发布时间】:2018-06-03 11:27:27
【问题描述】:

我正在使用 Lodash 按列对表中的数据进行排序。当我单击表格列标题中的箭头时,该特定表格列将按升序或降序排序。但是,我希望每列首先按升序排序,而不管其他列的当前顺序如何。现在,我的函数只根据当前方向切换升序和降序,而不考虑列。如何修复此功能?

export class TableComponent {
  @Input() data
  direction: string = ''

  sort(val) {
    if (this.direction === '' || this.direction === 'asc') {
      this.data = _.orderBy(this.data, [val], ['desc'])
      this.direction = 'desc'
    } else {
      this.data = _.orderBy(this.data, [val], ['asc'])
      this.direction = 'asc'
    }
    console.log(this.direction)
  }

}

table.component.ts

<table>
    <thead>
        <tr>
            <th *ngFor="let col of cols">
                {{col.header}}
                <input type="text" 
                [(ngModel)]=fields[col.value] 
                (ngModelChange)="handleFilterChange()" 
                (click)="selectCol(col.value)"
                *ngIf=col.enableFilter/>
                <img 
                class="arrow" 
                (click)="sort(col.value)"/>
            </th>
        </tr>
    </thead>
    <tbody *ngFor="let row of data | filter: filters:selectedCol">
        <tr>
            <td *ngFor="let col of cols">{{row[col.value]}}</td>
        </tr>
    </tbody>
</table>

【问题讨论】:

  • 请提供一些 plunker。我不清楚什么是“每列首先按升序排序,而不管其他列的当前顺序如何。”您是说每个特定行的列中的信息不相关,并且您只想对特定列的值进行排序而不考虑其他列的值吗?
  • 实际上,如果您想对每一列进行独立排序 - 那么只需为每一列使用单独的数组
  • 我的意思是我只想对特定列的值进行排序,而不管其他列当前是升序还是降序。现在它只是在两者之间切换。
  • 另外,我从一个端点获取我的数据,所以我不认为将每一列分离到自己的数组中是最好的方法。

标签: angular sorting lodash


【解决方案1】:

问题: 假设您必须呈现客户详细信息列表,其中包括客户姓名、加入日期、地址、电话等。加入日期在 JSON 响应中以字符串形式出现。

由于不可能将此“加入日期”(joinDate) 列排序为日期,并假设有另一个隐藏列以毫秒为单位提供此“加入日期”(joinDateInMs)。

解决方案:此列使用“cellRenderer”和“comarator”组合。 下面的代码 sn-p 是不言自明的。

columnDefs: [{
 headerName: “Join Date”, field: “joinDateInMs”,  
 cellRenderer: function (params) {
                return params.data.joinDate;
             }, 
comparator: self.createDateComparator
},
]
......
//
createDateComparator(date1, date2) {
        return date2 - date1;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 2012-11-08
    • 2023-03-07
    • 2016-03-03
    • 2018-10-08
    相关资源
    最近更新 更多