异步初始化 MatPaginator [英] Initialising MatPaginator asynchronously
问题描述
我们在 components
中初始化 MatPaginator 就像
@ViewChild(MatPaginator) 分页器:MatPaginator;
并分配给在我们的组件中定义为
的MatTable DataSource
matTableDataSource.paginator = this.paginator;
这在使用 async
管道和 *ngIf
的组合异步初始化数据源的用例中不起作用.作为,
<mat-table #table [dataSource]="yourData">...您的标题和列</mat-table><mat-paginator [pageSize]="10" showFirstLastButtons></mat-paginator>
注意:您可以使用 *ngIf
将 mat-paginator
放在 div
下方,但这不是理想的解决方案,如果您需要在带有单个后端异步调用的同一组件中显示多个表,则更是如此.
由于 mat-paginator
将异步初始化,因此使用如下代码将不起作用,因为 paginator
将为 null
.
ngAfterViewInit() {this.someDataObs = this.backendService.get().map(值=> {const matTableDataSource = new MatTableDataSource(value);matTableDataSource.paginator = this.paginator;//此处为空返回 matTableDataSource;});}
要让这种方法起作用,需要 MatPaginator
有一个 output 属性
在初始化后发出,但现在不存在.
使用 async
管道和 *ngIf
使代码非常简洁,您不应该避免使用它来克服这个用例.
实现这一目标的任何解决方案都会有所帮助.
在表格前加上这个 HIDDEN当 HIDDEN==TRUE 表不会在加载数据源之前呈现:
<mat-table [dataSource]="dataSource">...</mat-table>
We initialise MatPaginator in our components
like
@ViewChild(MatPaginator) paginator: MatPaginator;
and assign to a MatTable DataSource
defined in our component as
matTableDataSource.paginator = this.paginator;
This doesn't work in a use case when the data source is initialised asynchronously using async
pipe with a combination of *ngIf
. As,
<div *ngIf="someDataObs | async as yourData else loading">
<mat-table #table [dataSource]="yourData">
... your headers and columns
</mat-table>
<mat-paginator [pageSize]="10" showFirstLastButtons></mat-paginator>
</div>
Note: you could put mat-paginator
below the div
with *ngIf
, but that's not an ideal solution, more so if you need to show multiple tables in a same component coming with a single backend asynchronous call.
Since the mat-paginator
will get initialised asynchronously, using a code such as below will not work as paginator
will be null
.
ngAfterViewInit() {
this.someDataObs = this.backendService.get()
.map(value => {
const matTableDataSource = new MatTableDataSource<SomeType>(value);
matTableDataSource.paginator = this.paginator; // will be null here
return matTableDataSource;
});
}
To have a way for this to work would've required MatPaginator
to have an output property
to emit once initialised, but that doesn't exist for now.
Use of async
pipe and *ngIf
makes the code really concise and you should not avoid it to overcome this use case.
Any solution to achieve this would be helpful.
There is another solution on GitHub:
Just add this HIDDEN before the table While HIDDEN==TRUE the table will not be rendered before the dataSource is loaded:
<div [hidden]="isLoading">
<mat-table [dataSource]="dataSource">
...
</mat-table>
</div>
这篇关于异步初始化 MatPaginator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!