Angular 当数据源可见时,如何在角度材料数据表中启用排序<;T>;
我的组件中有一个下表Angular 当数据源可见时,如何在角度材料数据表中启用排序<;T>;,angular,angular-material,angular-material2,Angular,Angular Material,Angular Material2,我的组件中有一个下表 <table [dataSource]="(searchResults$ | async)?.accounts" mat-table matSort multiTemplateDataRows> <ng-container matColumnDef="Code"> <th *matHeaderCellDef mat-header-cell mat-sort-header> Account Co
<table [dataSource]="(searchResults$ | async)?.accounts" mat-table matSort multiTemplateDataRows>
<ng-container matColumnDef="Code">
<th *matHeaderCellDef mat-header-cell mat-sort-header> Account Code</th>
<td *matCellDef="let account" mat-cell> {{account.code}} </td>
</ng-container>
</table>
帐户代码
{{account.code}
我在列定义和表级别都保留了mat sort指令。-中提供的所有示例列出了从TS文件设置为不可观察流时的数据源。相同的方式。您只需对可观察对象中的元素进行排序
(matSortChange)=“sortData($event)”
然后对其进行排序:
sortData(sort: Sort) {
this.searchResults$ = this.searchResults$.pipe(map(results => {
// sort the results like in examples
}));
}
有一段时间我只是因为这件事把头撞在墙上,所以把它放在这里希望能节省一些时间。对我有用的是: 组件1.ts:
@Input() dataSource;
@ViewChild(MatSort, {static: true}) sort: MatSort;
ngAfterViewInit() {
this.dataSource.subscribe(data => {
this.dataSource = new MatTableDataSource(data);
this.dataSource.sort = this.sort;
});
}
component.html:
<app-table [dataSource]="yourService.getData()"></app-table>
将可观察对象传递到数据源时,请确保不要使用async
管道
我不熟悉Angular、TS和RxJS(通常与React一起使用),所以如果有人发现这种方法存在问题,请告诉我 如果需要加载(异步),则加载后需要呈现表并将排序设置为异步。试试这个
component.html
<loading-component *ngIf="isLoading$ | async"></loading-component> <--WHILE Loading
<div *ngIf="!(isLoading$ | async)"> <-- AFTER Loading
<ng-container *ngIf="dataSource.data.length >= 1; else noData"> <--Check if there's data
<table mat-table [dataSource]="dataSource" matSort>
...
</table>
</ng-container>
<ng-template #noData> <- In case there is not data (to not show the table/table-header)
...
</ng-template>
</div>
数据源应该是MatTableDataSource类型,所以在组件中更改它
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { Observable } from 'rxjs/Observable';
export class Component {
dataSource = new MatTableDataSource<any>();
isLoading$: Observable<boolean>;
private _sort: MatSort;
@ViewChild(MatSort) set matSort(ms: MatSort) {
this._sort = ms;
this.dataSource.sort = this._sort;
}
.. the rest of the component logic ...