我正在尝试从有角度的材料中使用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"}
谢谢
答案 0 :(得分:0)
好的,所以我通过在触发matSortChange
事件时实现自己的排序功能来解决了该问题,就像mat-sort-header
示例中一样。但这很奇怪,因为在其他示例中他们不需要这样做。