'Pagination doesn't update in customized angular directive when filtering (How to customize mat-paginator in angular material)
As Per Marshal's answer, I have implemented the customized directive in an angular material data table. But I'm facing pagination issues when filtering the data from the table. The pagination doesn't update when filtering.
Solution 1:[1]
We need in any way call to the function "initPageRange" of the directive when we make a filter, so first we need get the "directive". As the directive has as property "matPag" that is the paginator, we can make public this variable in constructor and the function initPageRange
constructor(
@Host() @Self() @Optional() private readonly matPag: MatPaginator,
private vr: ViewContainerRef,
private ren: Renderer2
)
//replace by
constructor(
@Host() @Self() @Optional() public readonly matPag: MatPaginator,
private vr: ViewContainerRef,
private ren: Renderer2
)
Equal with the function
private initPageRange(): void {
...
}
public initPageRange(): void {
...
}
we are going to get the "directive" using ViewChild, but we need get the MatPaginator becuase the paginator will be the property: matPag
-see the funciton ngOnInit()-
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
ngOnInit() {
this.dataSource.paginator = this.paginator;
}
@ViewChild(StylePaginatorDirective, { static: true }) paginator: StylePaginatorDirective;
ngOnInit() {
this.dataSource.paginator = this.paginator.matPag;
}
The last is add an input
<mat-form-field>
<mat-label>Filter</mat-label>
<input matInput (keyup)="applyFilter($event)" placeholder="Ex. Mia" #input>
</mat-form-field>
and the function applyFilter
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
setTimeout(() => {
this.paginator.initPageRange();
});
}
}
It's necesary enclodes in a setTimeout the function initPAgeRange to execute after Angular refresh the app
this is the forked stackblitz
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |