Angular Material: mat-paginator navigation disabled when length changes

119 views Asked by At

So basically, in my Angular app I have a list of elements (containing data retrieved from an API) that I'd like to control with mat-paginator. Here's what I've done:

results.component.html

<div class="results-list">
    <!-- Results list container. -->
    <div class="container">
      <app-result-card
        *ngFor="let result of results"
        [result]="result"/>
      <mat-paginator
        class="paginator"
        showFirstLastButtons
        (page)="handlePageEvent($event)"
        [length]="length"
        [pageSize]="pageSize"
        [pageIndex]="pageIndex"
        [pageSizeOptions]="pageSizeOptions"/>
    </div>
  </div>

results.component.ts

export class ResultsComponent{
  public results: VM[] = [];  // Custom model.
  public length = 0;
  public pageSize = 5;
  public pageIndex = 0;
  public pageSizeOptions = [5, 10, 25];

  constructor(
    private http: HttpClient
  ){}

  ngAfterViewInit(): void{
    this.http.get<VM[]>("http://localhost:8080/vm/get").subscribe(data => {
      this.results = data;
      this.length = Math.ceil(this.results.length/this.pageSize);
    })
  }

  handlePageEvent(e: PageEvent){
    this.pageSize = e.pageSize;
    this.pageIndex = e.pageIndex;
    this.length = Math.ceil(this.results.length / this.pageSize);
  }
}

The problem is that whenever the length value gets changed, the navigation button to go to the next page disables itself. I tested it by initializing the lenght value to 50, the pageIndex value to 3 and by disabling the assignation inside ngViewAfterInit, and when the page loads the "next page" button is fine, but when I go to the previous page (and so I call the handlePageEvent function) and the length gets changed, that button instantly disables. I've found this example (the "Configurable paginator") inside the documentation and, according to it, changing the length shouldn't be a problem. What am I doing wrong?

0

There are 0 answers