我一直在查看您在这里所做的事情,我认为由于 setData 函数,它对您不起作用。您在数据集中推送“描述”行的事实使排序功能感到困惑,因为它也想对其进行排序,但无法在“描述”对象中找到选定的列键。
此外,您有 2 个不同的 mat-row 项目这一事实令人困惑。
我想提出一个不同的解决方案,以更简洁的方式解决您的一些问题。
import { Component, AfterViewInit, ViewChild } from "@angular/core";
import { DataSource } from "@angular/cdk/table";
import { Observable } from "rxjs/Observable";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import "rxjs/Rx";
import { MatSort, MatTableDataSource } from "@angular/material";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class AppComponent implements AfterViewInit {
@ViewChild(MatSort) sort: MatSort;
dataSource: MatTableDataSource<any>;
isDescriptionRow = (index, item) => item.description;
displayedColumns = ['id', 'data'];
constructor() {
// this.dataSource = new MatTableDataSource<any>(this.setData(DATA));
this.dataSource = new MatTableDataSource<any>(DATA);
}
ngAfterViewInit() {
if (this.dataSource) {
this.dataSource.sort = this.sort;
this.dataSource.sortingDataAccessor = (item, property) => {
console.log(item);
return item[property];
};
}
}
// setData(vals: any[]) {
// const splitVals = [];
// vals.forEach(v => {
// splitVals.push({ data: v.data, id: v.id });
// splitVals.push({ description: v.description });
// });
// return splitVals;
// }
}
const DATA = [
{ data: "ABC", id: 1, description: "Blah blah info about ABC" },
{ data: "DEF", id: 2, description: "Blah blah info about DEF" },
{ data: "GHI", id: 3, description: "Blah blah info about GHI" },
{ data: "JKL", id: 4, description: "Blah blah info about JKL" },
{ data: "MNO", id: 5, description: "Blah blah info about MNO" }
];
您会注意到,我只是将数据保持原样,没有进行任何操作。
<app-header></app-header>
<div style="padding: 32px">
<mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="id">
<mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
<mat-cell *matCellDef="let item">
<div>{{item.id}}</div>
<div>{{item.description}}</div>
</mat-cell>
</ng-container>
<ng-container matColumnDef="data">
<mat-header-cell *matHeaderCellDef mat-sort-header> Data </mat-header-cell>
<mat-cell *matCellDef="let item">
{{item.data}}
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;" class="light-border">
</mat-row>
<!-- <mat-row *matRowDef="let row; columns: ['description']; when: isDescriptionRow">
</mat-row> -->
</mat-table>
</div>
现在您会注意到排序工作正常。
使用 css 进行一些调整可以帮助您以您想要的方式放置元素。
我已经在评论中留下了mat-row,我建议你把这段代码取消评论看看会发生什么,它会覆盖之前的mat-row。
我知道这不是您想要的,但也许它可以让您向前迈出一步,达到您想要的结果。
也许您将能够在更新依赖项后实现您正在寻找的东西。
看这个例子:
example of multiline rows
只需删除可扩展逻辑,您将看到多行行