typescript - 来自打字稿的角度更改管道参数
问题描述
当我单击标题时,我正在尝试对表格中的对象列表进行排序。
我已经尝试从 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 ?
解决方案
您也应该能够按照自己的方式进行操作,但是您需要具有触发更改检测和表重新呈现行的功能。
@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);
}
推荐阅读
- python - 样条与python scipy中的平面相交
- javascript - 允许在长度受限的字段中替换数字
- java - 如何编写标签中具有多个值(两行)的xpath
- symfony - 无法覆盖和使用 FOS 注册表单
- c - 为什么 i=i++ 的 i 值不增加;陈述?
- performance - Cortex M4 LDR/STR 时序
- adsense - 某些广告中的 Google Adsense 图片未显示在我的网站上
- r - 如何使用随机森林模型反向计算给定因变量的预测变量?
- javascript - 将 Service Worker 中的数据写入 Cloud Firestore
- python-3.x - 根据 Pandas 中的索引将一个数据帧拆分为多个