【问题标题】:Angular change pipe parameter from typescript来自打字稿的角度更改管道参数
【发布时间】:2020-03-05 18:11:25
【问题描述】:

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

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

【问题讨论】:

标签: typescript angular7


【解决方案1】:

您也应该能够按照自己的方式进行操作,但您需要有一个函数来触发更改检测和表格重新呈现行。

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

然后你打电话

this.table.renderRows()

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

this.ref.detectChanges()

你必须在你的构造函数中注入变化检测器引用:

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

【讨论】:

    猜你喜欢
    • 2013-08-16
    • 2019-05-08
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 2016-02-03
    相关资源
    最近更新 更多