首页 > 解决方案 > 来自打字稿的角度更改管道参数

问题描述

当我单击标题时,我正在尝试对表格中的对象列表进行排序。

我已经尝试从 TypeScript 对列表进行排序,然后更新绑定到表的变量,但列表重新出现,就像在排序之前一样。

//Set with a list from DB
public items: Items[]

let sort: Item[] = this.items.sort((a, b) => parseInt(a.id) - parseInt(b.id));
    console.log(sort);
    this.items = null;
    this.items = sort;

那么,是否可以像这样使用 OrderBy 管道:

*ngFor="let item of items | OrderBy:'asc':'propertyName'"

然后以编程方式更改 propertyName ?

标签: typescriptangular7

解决方案


您也应该能够按照自己的方式进行操作,但是您需要具有触发更改检测和表重新呈现行的功能。

@ViewChild(MatTable) table: MatTable<any>;

然后你打电话

this.table.renderRows()

并且根据您的变更检测策略,您可能还需要调用

this.ref.detectChanges()

然后,您必须在构造函数中注入更改检测器 ref:

constructor(private ref: ChangeDetectorRef) {}

但是 Angular 材料内置了这个功能,它的文档非常好,有很多最新的例子:

[网址]

这是一个例子,从那里复制粘贴:

<table matSort (matSortChange)="sortData($event)">
  <tr>
    <th mat-sort-header="name">Dessert (100g)</th>
    <th mat-sort-header="calories">Calories</th>
    <th mat-sort-header="fat">Fat (g)</th>
    <th mat-sort-header="carbs">Carbs (g)</th>
    <th mat-sort-header="protein">Protein (g)</th>
  </tr>

  <tr *ngFor="let dessert of sortedData">
    <td>{{dessert.name}}</td>
    <td>{{dessert.calories}}</td>
    <td>{{dessert.fat}}</td>
    <td>{{dessert.carbs}}</td>
    <td>{{dessert.protein}}</td>
  </tr>
</table>

 sortedData: Dessert[];

  constructor() {
    this.sortedData = this.desserts.slice();
  }

  sortData(sort: Sort) {
    const data = this.desserts.slice();
    if (!sort.active || sort.direction === '') {
      this.sortedData = data;
      return;
    }

    this.sortedData = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'calories': return compare(a.calories, b.calories, isAsc);
        case 'fat': return compare(a.fat, b.fat, isAsc);
        case 'carbs': return compare(a.carbs, b.carbs, isAsc);
        case 'protein': return compare(a.protein, b.protein, isAsc);
        default: return 0;
      }
    });
  }
}

function compare(a: number | string, b: number | string, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

推荐阅读