3

I would like to use the Angular mat-table with mat-paginator controlling the page changes with http request. So, I receive from my server an object with the following attributes:

content: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
first: true
last: false
number: 0
numberOfElements: 10
pageable: {sort: {…}, offset: 0, pageSize: 10, pageNumber: 0, paged: true, …}
size: 10
sort: {sorted: false, unsorted: true}
totalElements: 82
totalPages: 9
__proto__: Object

the attribute "number" is the number of the current page and "totalPages" the total of pages that I have.

I've tried to implement the mat-paginator like this:

<mat-paginator [length]="paginas" [pageSize]="10"></mat-paginator>

the variable "paginas" stores the atrribute "totalPages", and is showing correctly:

enter image description here

The problem is, as you can see, the arrows button preview and forward are disabled. I know that I have to do more implementation, but the official documentation of Angular Material doesn't show how to do it.

Murilo Góes de Almeida
  • 1,588
  • 5
  • 20
  • 42

1 Answers1

12

After some researchs and try and error tactics I've found a solution which solves my problem. I did 2 basic errors:

1) The [length] attribute in the mat-paginator tag is the number total of elements. So, I've used "totalElements" of my object instead of "totalPages", then, the arrow buttons start to work.

2) I've figured out that i need to set the [length] in a method called ngAfterViewInit()

My component now is like it:

  ngOnInit() {     
  }

  ngAfterViewInit(): void {
    this.gestaoAcessoService.getAllUsuarioPage(this.page)
    .subscribe(data => 
      { 
        this.usuarios = data['content'];
        this.length = data['totalElements'];
      })
  }

  setPage(event) {
    this.page = event.pageIndex;
    this.getUsers();
}

  getUsers() {
    this.gestaoAcessoService.getAllUsuarioPage(this.page)
    .subscribe(data => 
      { 
        this.usuarios = data['content'];
        this.length = data['totalElements'];
      })
  }

and in my html i added (page)="pageEvent = setPage($event)" You have to declare only the method "setPage(event)", in this case I just take the pageIndex and ask the server to the next page;

<mat-paginator [length]="length" [pageSize]="10" [showFirstLastButtons]="true" (page)="pageEvent = setPage($event)">
</mat-paginator>
Murilo Góes de Almeida
  • 1,588
  • 5
  • 20
  • 42