首页 文章

角度材料2:如何区分一个组件中的两个或多个可排序表?

提问于
浏览
0

亲爱的Stackoverflow社区,

根据Angular material 2文档,您可以向表中添加mdSort指令:

排序使用mdSort指令并在表的列 Headers 中添加排序UI . 排序标头发出可用于通过表的数据源触发更新的事件 .

Code : component.html

使用mdSort指令和md-sort-headers

<md-table fxFlex="100%" #table [dataSource]="dataSource" mdSort>

              <ng-container mdColumnDef="category">
                <md-header-cell *mdHeaderCellDef md-sort-header> Category </md-header-cell>
                <md-cell (click)="alert(element)" *mdCellDef="let element"> {{element.category}} </md-cell>
              </ng-container>
             ...
             ...
</md-table>

Code: component.ts

引用sort指令:

@ViewChild(MdSort) sort: MdSort;

在数据源中注入它:

this.dataSource = new ExampleDataSource(this.exampleDatabase, this.sort);

并使用它来排序对象:

getSortedData(): Task[] {
const data = this._exampleDatabase.data.slice();
if (!this._sort.active || this._sort.direction === '') { return data; }

return data.sort((a, b) => {
  let propertyA: number|string|boolean = '';
  let propertyB: number|string|boolean = '';

  switch (this._sort.active) {
    case 'category': [propertyA, propertyB] = [a.category, b.category]; break;
    case 'task': [propertyA, propertyB] = [a.task, b.task]; break;
    case 'favorite': [propertyA, propertyB] = [a.favorite, b.favorite]; break;
  }

  let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
  let valueB = isNaN(+propertyB) ? propertyB : +propertyB;

  return (valueA < valueB ? -1 : 1) * (this._sort.direction === 'asc' ? 1 : -1);
});

}

现在我想要另一个可排序的表,我已经创建了另一个数据源,数据库等 .

But how do I differentiate to mdSort directive?

1 回答

  • 1

    绑定到指令在指令中使用 exportAs -attribute工作,请参阅此参考:Angular 2: Get reference to a directive used in a component

    但这不适用于您的示例,因为您使用的是第三方库而MdSort没有 exportAs -property


    如果要绑定到组件,可以使用以下标签为每个表提供唯一的ID:

    <md-table fxFlex="100%" #table1 [dataSource]="dataSource1" mdSort>
    </md-table>
    <md-table fxFlex="100%" #table2 [dataSource]="dataSource2" mdSort>
    </md-table>
    

    然后你可以像这样独特地得到孩子:

    @ViewChild('table1') table1: MdTable;
    @ViewChild('table2') table2: MdTable;
    

相关问题