Home > other >  I have an angular paginator that stops working when showing and hiding it using an ngIf
I have an angular paginator that stops working when showing and hiding it using an ngIf

Time:04-09

Here is a demonstration of the issue - https://stackblitz.com/edit/angular-rtucth?file=src/app/table-pagination-example.html

Steps to reproduce:

  1. Notice the paginator displays 1-5 of 20
  2. Click the button labeled show or hide using ngIf to hide the table
  3. Click the button labeled show or hide using ngIf to show the table
  4. Notice the paginator now displays 0 of 0

Why does the paginator stop working when it is shown again?

CodePudding user response:

This is because you remove the paginator. When you ngIf it again into the view, the paginator in the view is NO LONGER THE SAME PAGINATOR INSTANCE it was when you was calling ngAfterViewinit()

  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngAfterViewInit() {
    //Assigning original paginator!
    this.dataSource.paginator = this.paginator; 
  }

So you end up with paginator that no longer exists in view to be bound to the MatDataSource

To overcome that, you can change to QueryList and assign paginator whenever new one comes into the view.

eg

@ViewChildren(MatPaginator) paginator: QueryList<MatPaginator>;

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator.first;
    this.paginator.changes.subscribe(() => {
      this.dataSource.paginator = this.paginator.first;
    });
  }

https://stackblitz.com/edit/angular-rtucth-d2fpth?file=src/app/table-pagination-example.ts

Another way youwl be to add set/get accessors to paginator field reassign on every set.

It all comes down to the same thing - reasigning paginator that currently came into the view

CodePudding user response:

You are destroying the component and creating a new one. The reference you set in the initialization of the component is no longer available.

ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
}

You'll need to use the [hidden] attribute, instead of *ngIf to achieve what you're expecting.

  • Related