打字稿中的角度更改管道参数

时间:2020-03-05 10:00:44

标签: typescript angular7

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

我已经尝试过从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?

1 个答案:

答案 0 :(得分:1)

您也应该能够做到这一点,但是您需要具有一个触发变更检测和表重新呈现行的功能。

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

然后致电

this.table.renderRows()

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

this.ref.detectChanges()

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

constructor(private ref: ChangeDetectorRef) {}

但是随后Angular材料内置了此功能,有关此文档非常出色,其中包含了许多最新示例:

[URL]

这是一个示例,从那里粘贴粘贴:

<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);
}