出于某种原因,表面上的垫子排序会移动箭头,因此排序应该可以,但不能排序...
这是HTML:
<div class="mat-elevation-z8">
<table mat-table [dataSource]="dataSource" matSort>
<!-- name -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{ model.fields.name.label }}</th>
<td mat-cell *matCellDef="let element"> {{ element.name }} </td>
</ng-container>
<!-- ... -->
</table>
</div>
在我的component.ts中:
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
export class DevizaListComponent implements OnInit {
dataSource = new MatTableDataSource<DevizaInterface>(devizas);
devizas: DevizaInterface[] = [
{
name: 'dollar',
code: 'USD' ,
},
//...
//...
];
//...
@ViewChild(MatSort, { static: true }) sort: MatSort;
//...
constructor() { }
ngOnInit() {
this.dataSource.sort = this.sort;
}
}
我在我的app.module.ts中导入了这个
import { MatTableModule } from '@angular/material/table';
import { MatSortModule } from '@angular/material/sort';
@NgModule({
imports: [
MatTableModule,
MatSortModule,
],
})
控制台不显示错误消息。箭头出现在排序界面上但表未按应排序的原因是什么?
答案 0 :(得分:0)
很可能在将this.sort
内的this.dataSource.sort
分配给ngOnInit
时尚未定义。因此,dataSource
不接收排序事件。这可能是由于结构指令(即*ngIf
)仅在模板中有条件地包含了表格所致。
可以通过更改static
上的@ViewChild
值并在ngAfterViewInit
生命周期钩子内分配sort
来解决该问题。请查阅有关component's livecycle的Angular文档。
export class DevizaListComponent implements AfterViewInit {
...
@ViewChild(MatSort, { static: false}) sort: MatSort;
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
还应该更改类成员的顺序,并在初始化
dataSource
之后创建devizas
。