Issue with Pagination in Angular 7: Functioning Error

I am having trouble with my pagination setup. I am struggling to understand how to properly pass this.total = res.totalPage; from the Component to the Service so that it can count the pages correctly. Currently, it is only displaying one page as shown in this "image reference". Below, I have provided the html, Component, and Service code to make it easier for you to follow along. In the html code, I have only displayed a portion of the pagination.

HTML

    <table
      mat-table
      [dataSource]="dataSource"
      matSort
      multiTemplateDataRows
      class="mat-elevation-z8-"
    >
    <ng-container
        matColumnDef="{{ column }}"
        *ngFor="let column of columnsToDisplay | paginate: { id: 'server', itemsPerPage: 10, currentPage: p, totalItems: total }"
      ><!-- -->
      <ng-container *ngIf="column === 'select'; else notSelect">
        <th mat-header-cell *matHeaderCellDef>
          <mat-checkbox (change)="$event ? masterToggle() : null"
                        [checked]="selection.hasValue() && isAllSelected()"
                        [indeterminate]="selection.hasValue() && !isAllSelected()">
          </mat-checkbox>
        </th>
        <td mat-cell *matCellDef="let row">
          <mat-checkbox (click)="$event.stopPropagation()"
                        (change)="$event ? selection.toggle(row) : null"
                        [checked]="selection.isSelected(row)"
                        >
          </mat-checkbox>
        </td>
      </ng-container>

      <ng-container *ngIf="column.length == 11"  matColumnDef="name"><!---->
        <th mat-header-cell *matHeaderCellDef mat-sort-header><strong>{{ column }}</strong></th>
      </ng-container>
      <ng-container #headerSort><!---->
        <th mat-header-cell *matHeaderCellDef><strong>{{ column }}</strong></th>
      </ng-container>
        <td
          mat-cell
          *matCellDef="let element"
          (click)="open(element)"
          class="pointer"
        >
        <p>
         {{element.name}}
         </p>
         <p *ngIf="column.length == 7">
            {{element.location}}
          </p>
          <p *ngIf="column.length == 6">
              {{element.status}}
          </p>
          <p *ngIf="col length == 8">
            {{date}}
        </p>
        </td>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
      <tr
        mat-row
        *matRowDef="let element; columns: columnsToDisplay"
        class="example-element-row"
        [class.example-expanded-row]="expandedElement === element"

      ></tr>

      <tr
        mat-row
        *matRowDef="let item; columns: ['expandedDetail']"
        class="example-detail-row"
      ></tr>
    </table>
    <pagination-controls (pageChange)="loadAgents($event)" id="server"></pagination-controls>

Component

ngOnInit() {
    this.getPage(1);
}

getPage(page: number) {
  this.allService.getAllService(pageIndex).subscribe(res =>{
  this.dataSource = new MatTableDataSource<AllDetails>(res['allList']);

  this.total = res.totalPage;
  console.log(this.total)
  this.p = pageIndex;
  this.dataSource.sort = this.sort;

 }
}

Service

getAllService(page:number): Observable<any>  {
    console.log("TEST page back" +page)
    const urls: string = `http://192.168.0.101:9080/project/api/listall/${orgId}`
   const requestUrl: string = `${urls}/${page + 1}/desc`;

    return this.http.get<AllDetails>(requestUrl).pipe(map(res => {
      return {
        allList: res['allList'],
        noPage: res['noPage'],
        totalPage: res['totalPage']
      };
  }));

  }

The part noPage: res['noPage'] refers to the current page being displayed.

I have an example of pagination code, but I am unsure how to implement it into my current code.

Any help would be greatly appreciated.

Thank you in advance.

Answer №1

Consider making a modification

<ng-container matColumnDef="{{ column }}" *ngFor="let column of columnsToDisplay | 
  paginate: { id: 'server', itemsPerPage: 10, currentPage: p, totalItems: total }">

to

<ng-container matColumnDef="{{ column }}" *ngFor="let column of columnsToDisplay | 
async | paginate: { id: 'server', itemsPerPage: 10, currentPage: p, totalItems: total }">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Working with Angular: Accessing SCSS variables from style.scss using JavaScript inside a component

I am working on an Angular 9 application that utilizes Angular Material and has two themes, namely dark and light. These themes are defined in the style.scss file as follows: $rasd-dark-text-color: mat-palette($mat-grey, 300); $rasd-light-text-color: mat-p ...

Ways to showcase information based on the chosen option?

Is there a way to display data based on the selected value in a more efficient manner? Currently, when clicking on a value from the list on the left side, new data is added next to the existing data. However, I would like the new data to replace the existi ...

Are you looking to resolve TypeScript warnings related to imports managed by Webpack loaders?

Setting up a new project with Svelte, Webpack, and TypeScript based on this template. Ran the scripts/setupTypeScript.js script to switch to TypeScript after initial setup. Encountering errors in VSCode and TypeScript when importing non-TypeScript files: ...

What is the best way to share type definitions between a frontend and a Golang backend application?

I utilized typescript for both the frontend (Angular) and backend (Express). To ensure type definitions are shared, I created a file called shared-type-file.ts. interface Kid{ name: string; age: number; } By then running npm install in both the front ...

Unable to select multiple checkboxes as they are unresponsive and not registering any clicks

I am facing an issue with rendering multiple checkboxes in a grid cell. I attempted to use formly multicheckbox, but unfortunately the checkboxes did not render properly. So I decided to try a different approach, however, now the checkboxes are not being c ...

How can I retrieve the express Application within a REST API?

After reviewing Massive's documentation and learning that saving the connection object to Express's application settings can help reduce database connection execution time, I encountered a problem. How can one access the Express app variable when ...

Utilizing CSS classes to style custom day templates in ng-bootstraps datepicker

Currently, I am utilizing ng-bootstraps datepicker to showcase user data on a daily basis. I have implemented a custom day template to apply specific CSS classes. <ng-template #customDay let-date> <div class="custom-day" [ngCla ...

Utilize JavaScript libraries in a TypeScript project

Looking to integrate a payment system called iyzico into my project. The iyzico payment library can be found here. However, there are no types available for it. How can I utilize this library in my Node.js TypeScript Express backend project? I attempted t ...

Encountered Error: Unknown property 'createStringLiteral', causing TypeError in the Broken Storyshots. This issue is happening while using version ^8.3.0 of jest-preset-angular

When I upgraded to jest-angular-preset ^8.3.0 and tried to execute structural testing with npm run, I encountered the following error: ● Test suite failed to run TypeError: Cannot read property 'createStringLiteral' of undefined at Obje ...

Using a dictionary of objects as the type for useState() in TypeScript and React functional components

I am in the process of transitioning from using classes to function components. If I already have an interface called datasets defined and want to create a state variable for it datasets: {[fieldName: string]: Dataset}; Example: {"a": dataset ...

The TypeScript Type inside the Node Module Doesn't Seem to Be Functioning

In my React project, I am using the material-ui@next library along with typescript. Below is the code snippet that I have written: <CardMedia image={item.image_url} style={{ width: 238, height: 124.5 }} /> However, when I try to compile this code, ...

What is the best way to incorporate multiple pages and export them in an angular2 project?

Having some issues with my code. Can anyone lend a hand? import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: `page1.html` }) @Component({ selector: 'my-app2', templateUrl: `page2.html` ...

The type 'undefined' cannot be assigned to a different type within the map() function, resulting in a loss of type information

I am facing an issue in my redux toolkit where an action is trying to set some state. Below is the relevant code snippet: interfaces export interface ProposalTag { id: number; name: string; hex: string; color: string; } export interface ProposalS ...

Using Angular to bind the ngModel to a variable's object property

In my application, I am working with a user object that looks like this: let user = {name: "John", dob:"1995-10-15", metadata: {}} The metadata property of the user object is initially empty. I want to add a new property to the metadata object based on u ...

Unveiling the Power of Ionic and React for Component Repetition

I'm having trouble figuring out how to repeat my component multiple times using react in Ionic. Can someone assist me with this? Here's an example: In my Component.tsx file, I have the following code: import React from 'react'; import ...

Jest is having trouble locating the module that ends with ".svg?react" when using Vite in combination with React, TypeScript, and Jest

Currently, I am facing an issue while testing my app built using vite + react + ts. Jest is highlighting an error stating that it cannot locate the "svg?react" module when trying to create my dashboard component. The problem arises with Jest as soon as th ...

Tips for managing 'single click' and 'double click' events on a specific html element in typescript:Angular 2 or 4

My problem lies in the fact that both events are activated when I double click. For instance, I want distinct functionality to occur for each event trigger. <a (click)="method1()" (dblclick)="method2()"> Unfortunately, both method1() and method2() ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

Dealing with the "net::ERR_CERT_DATE_INVALID" issue within Ionic 4

When sending an "http" request in Ionic4, the response neither falls under the success callback nor gets handled by the error handling block. It just keeps loading indefinitely. I need a solution to properly handle this error in Ionic4 (Client side). I at ...

Deactivating an emitted function from a child component in Angular 4

There is a main component: @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { funcBoo():void{ alert("boo"); //return fal ...