带分类和分页器的角材料表

时间:2018-12-02 11:45:52

标签: angular angular-material paginator

我在项目中使用角材料表。该表的数据将通过输入由父组件过去。这很好。我也想在表中添加一个分页器,并且一列应该是可排序的。但是在设置排序和分页器时,出现错误“ ....无法设置未定义的.sort”。

<div id="table-overflow">
    <mat-table [dataSource]="dataSourceLog" class="mat-elevation-z8" matSort matSortDisableClear>
        <ng-container matColumnDef="actionTS">
            <mat-header-cell *matHeaderCellDef mat-sort-header>TimeStamp</mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.actionTSFormated}} </mat-cell>
        </ng-container>
        /* some more columns*/
        <mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>
</div>
<mat-paginator [pageSizeOptions]="[10, 20, 50]" showFirstLastButtons></mat-paginator>

.ts文件

export class ProtocolLogTable implements OnInit{
    @Input() dataSourceLog: MatTableDataSource<DataLog>;
    timestampFrom: string;
    timestampTo: string;

    displayedColumns: string[] = ['actionTS' /* some more columns */];

    @ViewChild(MatPaginator) paginator: MatPaginator;
    @ViewChild(MatSort) sort: MatSort;

    ngOnInit() {
        this.dataSourceLog.sort = this.sort;
        this.dataSourceLog.paginator = this.paginator;
    }
}

1 个答案:

答案 0 :(得分:1)

创建组件后,可能不会立即获取数据。尝试将您的代码从ngOnInit移至@Input设置器中

public dataSourceLogValue: MatTableDataSource<DataLog>;

@Input()
public set dataSourceLog(value: MatTableDataSource<DataLog>) {
  if (value) {
    this.dataSourceLogValue = value;
  }
}

并确保在模板中将dataSourceLog重命名为dataSourceLogValue