角垫表试图实现垫排序

时间:2019-11-19 10:37:31

标签: angular angular-material mat-table angular-material-table

我正在尝试在席子表上实现席子排序,但是在尝试初始化席子排序功能时遇到了一些问题。 排序属性未定义:

enter image description here

垫子表:

<mat-table matSort #sort1="matSort" matSortActive="id" matSortDirection="asc" matSortDisableClear
                                               #table
                                               [dataSource]="dataSource">
                                        <ng-container matColumnDef="statusName">
                                            <mat-header-cell *matHeaderCellDef mat-sort-header="customer.statusName">Status Name</mat-header-cell>
                                            <mat-cell *matCellDef="let customer">
                                                {{customer.statusName}}
                                            </mat-cell>
                                        </ng-container>
                                    </mat-table>

组件代码:

@ViewChild('sort1', { static: true }) sort: MatSort;
ngOnInit(): void {

    const sortSubscription = this.sort.sortChange.subscribe(() => (this.paginator.pageIndex = 0));
    this.subscriptions.push(sortSubscription);

    this.dataSource = new InvoiceStatusDataSource(this.invoiceStatusService);

    this.loadItems(true);
}

在loadItems中,我有这个:

 loadItems(firstLoad: boolean = false) {
        const queryParams = new QueryParamsModel(
            {},
            this.sort.direction,
            this.sort.active,
            this.paginator.pageIndex,
            this.paginator.pageSize
        );
        this.dataSource.loadItems(queryParams);
        this.selection.clear();
    }

如您在顶部的屏幕快照中所见,sort属性是未定义的。 我是否需要编写一些额外的代码来初始化该属性?

1 个答案:

答案 0 :(得分:0)

您的MatTable是否封装在任何ngIf中?如果为true,则必须在ngAfterViewInit中设置排序,因为您的表未呈现且您的'MatSort'不存在,或者您可以添加一个setter来设置MatSort时的设置。

@ViewChild('sort1', { static: false})set matSort(value: MatSort){
  if(this.dataSource && value) {
    this.dataSource.sort = value;
  }
}
```
相关问题