我正在尝试使用角材料中的 mat-sort-header 来对表格进行排序。
我从 http 请求中获取表中包含的数据。数据显示正常,但排序似乎不起作用。单击列时,我可以看到发出的事件,但行保持相同的顺序。
我已经看到有些人已经遇到了这个问题,所以我尝试了以下方法:
将内部包装
this.dataSource.sort = this.sort
为 setTimeOut在 ngOnViewInit 中执行此操作
这是我的 html 模板:
<div class="example-container mat-elevation-z8">
<table mat-table [dataSource]="nagiosData" matSort (matSortChange)="sortData($event)">
<ng-container matColumnDef="hostName">
<th mat-header-cell mat-sort-header *matHeaderCellDef> Host name </th>
<td mat-cell *matCellDef="let element"> {{element.hostName}} </td>
</ng-container>
<ng-container matColumnDef="pluginOutput">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Plugin output </th>
<td mat-cell *matCellDef="let element"> {{element.pluginOutput}} </td>
</ng-container>
<ng-container matColumnDef="currentState">
<th mat-header-cell *matHeaderCellDef mat-sort-header> State </th>
<td mat-cell *matCellDef="let element">
<span *ngIf="element.currentState == 0; else red" class="dot"></span>
</td>
</ng-container>
<ng-container matColumnDef="services">
<th mat-header-cell *matHeaderCellDef> Services </th>
<td mat-cell *matCellDef="let element"> <button mat-raised-button color="primary">See Services</button> </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<ng-template #red>
<span class="redDot"></span>
</ng-template>
和我的组件:
import {Component, OnInit, ViewChild, AfterViewInit} from '@angular/core';
import {DataLoaderService} from '../data-loader.service';
import {MatPaginator, MatTableDataSource, MatSort, MatTable} from '@angular/material';
@Component({
selector: 'app-nagios-view',
templateUrl: './nagios-view.component.html',
styleUrls: ['./nagios-view.component.css']
})
export class NagiosViewComponent implements OnInit, AfterViewInit {
public data = [];
public nagiosData = [];
displayedColumns: string[] = ['hostName', 'pluginOutput', 'currentState', 'services'];
dataSource: MatTableDataSource<any>;
@ViewChild(MatTable) table: MatTable<any>;
@ViewChild(MatSort) sort: MatSort;
constructor(private dls: DataLoaderService) { }
public loadNagiosData(){
this.dls.getNagiosInfo().subscribe( data => {
this.nagiosData = JSON.parse(data.mesureList[0].description).hosts;
this.dataSource = new MatTableDataSource(this.nagiosData);
setTimeout(() => {
this.dataSource.sort = this.sort;
});
})
}
sortData(e) {
console.log(e);
}
ngOnInit() {
}
ngAfterViewInit(): void {
// this.loadData();
this.loadNagiosData();
}
我从 http 获得的数据是具有以下结构的元素数组:
{hostName: "someHostName", pluginOutput: "someString", services: Array(8), currentState: "0"}
谢谢