Search code examples
angularpaginator

How to pass numeric value from backend to a variable in angular frontend


I'm very new to angular and I have this problem that looked simple in the beginning!

I'm trying to implement this angular material paginator: https://material.angular.io/components/paginator/examples

In this component I get the data from the backend, with the method filterMessages. Now, in those data there is the total number of elements (the length for the paginator), which i get using values.totalElements. I assign this value to the totalLength variable. I want now to update the lentgh of the paginator with this new value.

    export class MessageComponent {

      constructor(...) {
      }

      totalLength: number;


      filterMessages(params: Params) {
        this.service.getMessages(params).subscribe(values => { // getMessages gets the data from the backend

          this.totalLength = values.totalElements  // here I get an value

          values = values.content;
          ...
        }, error => {
          ...
        });
      }

      // MatPaginator Inputs
      length = this.totalLength; // I want to update this with the value from the backend
      pageSize = 10;
      pageSizeOptions: number[] = [];

      // MatPaginator Output
      pageEvent: PageEvent;

}

Here is the .html implementation, it is the same as in the angular material example

<mat-paginator [length]="length"
               [pageSize]="pageSize"
               [pageSizeOptions]="pageSizeOptions"
               (page)="pageEvent = $event">
</mat-paginator>

<div *ngIf="pageEvent">
  <h5>Page Change Event Properties</h5>
  <div>List length: {{pageEvent.length}}</div>
  <div>Page size: {{pageEvent.pageSize}}</div>
  <div>Page index: {{pageEvent.pageIndex}}</div>
</div>

I would appreciate any idea, suggestion or example.


Solution

  • You're changing the value of totalLength and making the wrong assumption that it is connected to the length attribute (just because you initialize length = this.totalLength). This approach can work in a worksheet but definitely doesn't work here. You're not passing a reference to length at initialization, just a value. So it'll work if you do something like:

    filterMessages(params: Params) {
      this.service.getMessages(params)
        .subscribe(
          values => {
            this.length = values.totalElements;
            ...
          }, 
          error => {...}
        );
    }