我有Angular的最新版本和material组件的最新版本。 我尝试呈现在Tab控件内的表。但是,我无法进行排序操作。请帮忙。这里的代码: 查看:
<div class="container">
<div id="content">
<div id="main-content">
<div>
<mat-form-field>
<input matInput placeholder="Category Name" name="keyword" [(ngModel)]="keyword">
</mat-form-field>
<mat-checkbox [(ngModel)]="isActive" name="isActive">Active only</mat-checkbox>
<button mat-button type="button">Search</button>
</div>
<mat-tab-group (selectedTabChange)="onTabChange($event)">
<mat-tab [label]="sysCategory.name" *ngFor="let sysCategory of systemCategories">
<div>
<table mat-table matSort matSortDisableClear [dataSource]="dataSource?.items" class="mat-elevation-z4">
<tr>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Category</th>
<td mat-cell *matCellDef="let element">
<mat-form-field *ngIf="element.inEditMode">
<input matInput placeholder="Category" required maxlength="255" [(ngModel)]="element.name" />
</mat-form-field>
<span *ngIf="!element.inEditMode">{{element.name}}</span>
</td>
</ng-container>
</tr>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
</mat-tab>
</mat-tab-group>
</div>
</div>
</div>
组件:
export class CategoriesListComponent implements OnInit, AfterViewInit {
displayedColumns: string[] = ['name', 'delete', 'edit'];
dataSource: ResultsList<CategoryModel>;
systemCategories: SystemCategoryModel[];
sysCategoryId: number;
isActive = true;
keyword: '';
@ViewChild(MatSort) sort: MatSort = new MatSort();
constructor(private systemCategoriesService: DictionaryService, private categoriesService: CategoriesService) { }
ngOnInit() {
this.systemCategoriesService.getDictionary<SystemCategoryModel>(SystemCategoriesUrl)
.subscribe(v => { this.systemCategories = v; });
}
ngAfterViewInit() {
// S.O.S it doesnt work here for sure!
// this.sort.sortChange.subscribe(() => this.loadGrid());
}
onTabChange(tabChangeEvent: MatTabChangeEvent) {
this.sysCategoryId = this.systemCategories[tabChangeEvent.index].id;
this.loadGrid();
}
loadGrid() {
const query = this.createQuery();
this.categoriesService.load(query).subscribe(v => this.dataSource = v);
}
private createQuery(): CategoriesSearchQuery {
return {
isActive: this.isActive,
keyword: this.keyword,
pageIndex: 0,
pageSize: 1000,
sortField: this.sort && this.sort.active || 'name',
isDesc: this.sort && this.sort.direction === 'desc' || false,
systemCategoryId: this.sysCategoryId
};
}
答案 0 :(得分:1)
将此@ViewChild(MatSort) sort: MatSort = new MatSort();
更改为简单的@ViewChild(MatSort) sort: MatSort;
。
此外,您还需要将MatSort
分配给数据源,例如:this.dataSource.sort = this.sort;
,这通常是在ngOnInit()
中完成的。
有关更多信息,请查看官方Angular Material examples, 有一个带有过滤功能的表格示例,该表格应涵盖您的 需求。
如果您在多个选项卡上具有多个表和数据源,建议您将它们分开,不要重用同一数据源和MatSort
,因为这将提供一些奇怪的行为。我会通过当前所在的标签为数据编制索引,然后相应地显示数据源。
我进行了一次快速而肮脏的堆叠突击here,以展示其外观。