Implementing pagination for an Angular Material table using an HTTP request to set the page

How can I update the table page index when users click on next and previous buttons in an API that fetches data based on a specified Page number? It's important to note that I have already created a shared table.

 @Input() columns: Column[] = [];
 @Input() rows!: Row<T>[];

 @ViewChild(MatSort, { static: true }) matSort!: MatSort;
 @ViewChild(MatPaginator, { static: false }) matPaginator!: MatPaginator;
 @Input() isPageable = false;
 @Input() paginationSizes: number[] = [5, 10, 15];
 @Input() defaultPageSize = this.paginationSizes[1];
 pageNo = 0;
 @Input() PageIndex = 0;
 public dataSource = new MatTableDataSource<Row<T>>();
 public columnNames: string[] = []

 constructor(private cd: ChangeDetectorRef) { }

  ngOnInit(): void {
  this.dataSource.data = this.rows;
  this.columnNames = this.columns.map((column) => column.name.toString());
  this.dataSource.paginator = this.matPaginator;}

  ngAfterViewInit(): void {
  this.dataSource.paginator = this.matPaginator;}
 
  pageEvents(event: any) {
  console.log("PageIndex " + "=" + event.pageIndex);
  if (event.pageIndex > this.pageNo) {
  this.PageIndex = event.pageIndex
  console.log(this.PageIndex)

Answer №1

Simply subscribe to paginator.page for smooth pagination

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.paginator.page.subscribe(res=>{
      //res contains important page information
      {length:...,pageIndex:..,pageSize:...,previousPageIndex:..}
    })
  }

IMPORTANT: For a comprehensive example including filter/sorted and paginator functionalities, refer to this Stack Overflow post

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

Tips for effectively passing generics to React Hooks useReducer

I am currently working with React Hooks useReducer in conjunction with Typescript. I am trying to figure out how to pass a type to the Reducer Function using generics. interface ActionTypes { FETCH, } interface TestPayload<T> { list: T[]; } inter ...

Directly mapping packages to Typescript source code in the package.json files of a monorepo

How can I properly configure the package.json file in an npm monorepo to ensure that locally referenced packages resolve directly to their .ts files for IDE and build tooling compatibility (such as vscode, tsx, ts-node, vite, jest, tsc, etc.)? I want to a ...

Tips for showing nested JSON data in a PrimeNG table within Angular version 7

I am struggling to display nested json data in a PrimeNG table. When I retrieve the data using an HTTP service, it appears as [object][object] when displayed directly in the table. What I want is to show the nested json data with keys and values separated ...

The file or directory npx-cli.js cannot be found in the specified location: ../npm/bin/

Problem Description After creating a new React project using the command below, npx create-react-app my-app --template typescript and utilizing node version v18.15.0, I attempted to set up Prettier for the project following the instructions in the Pretti ...

Enhance your TypeScript React development with NeoVim

As a newcomer to vim, I decided to test my configuration with react and typescript. To do this, I created a simple demo app using the command npx create-react-app demo --template typescript. Next, I opened the directory in neovim by running nvim .. However ...

What could be causing TypeScript to forego type inference and default to 'any' in this scenario?

While refactoring parts of our React app in TypeScript, I encountered a challenge that required me to use what I consider to be a less than ideal double type argument. I'm unsure if this is a bug in TypeScript or if there is some type ambiguity causin ...

Exploring Angular 4: Leveraging mockRespond in Conjunction with RxJS Observables

I recently completed the development of an application that is functioning smoothly. Now, I am in the process of creating a test for it. The core functionality involves fetching items from an API backend: export class CatfactService { constructor(p ...

Generate barcodes using Angular 2

Can anyone point me in the direction of an Angular 2 Barcode Generator capable of creating code 128 barcodes? I've been searching but haven't had any luck finding one. If you have any suggestions or can offer assistance, it would be greatly appr ...

Mistakes following update to Angular 4 from Angular 2

After upgrading from Angular2 to Angular4, I encountered these errors in the CLI. While my app continues to function after the upgrade, I am curious about possible solutions to resolve these errors. Any suggestions? https://i.stack.imgur.com/CyYqw.png He ...

Accurate TS declaration for combining fields into one mapping

I have a data structure called AccountDefinition which is structured like this: something: { type: 'client', parameters: { foo: 3 } }, other: { type: 'user', parameters: { bar: 3 } }, ... The TypeScript declaration ...

Error in ReactJS VSCode while integrating Cypress testing: The name 'cy' cannot be found

Currently working on a ReactJS Typescript project using NPM and VSCode. Despite all my Cypress tests running smoothly, I am encountering a syntax error in VSCode: Error: Cannot find name 'cy' Any ideas on how to resolve this issue? https://i.ss ...

Using Promise<void> instead of Promise<any> is the preferred approach

Working with AngularJS, I have created several asynchronous functions that all use the same signature, which is app.Domain.GenericModel.EntityBase (my generic model). Here is an example: get(resource: string): ng.IPromise<app.Domain.GenericModel.Entity ...

An error persists in PhpStorm inspection regarding the absence of AppComponent declaration in an Angular module

After creating a new Angular application, I am encountering the issue of getting the error message "X is not declared in any Angular module" on every component, including the automatically generated AppComponent. Despite having the latest version of the An ...

The real file that was brought in after indicating a module in the node_modules directory that was coded in Typescript

After creating a typescript module named moduleA, I am ready to publish this package and make it accessible from another typescript project. Currently, for testing purposes, I have installed 'moduleA' using 'npm install ../moduleA'. Th ...

Testing MatDialog functions in Angular: Learning how to open and close dialogues

I am currently facing an issue with testing the MatDialog open and close functions. No matter what I try, I cannot seem to successfully test either the open or close functions. I am wondering how I can mock these functions in order to properly test them. W ...

Encountering a timeout error when trying to test the video element with Jest

My function extracts meta data such as width and height from a video element in the following code snippet: export async function getVideoMetadata( videoBlobUrl: string, videoElement: HTMLVideoElement, ): Promise<{ width: number; height: number }> ...

What is the best way to verify the presence of a route in Angular with Jasmine testing framework?

I'm currently in the process of developing a test to verify the presence of a specific route within my Angular application using Jasmine: import { routes } from './app-routing.module'; import { UsersComponent } from './users/users.comp ...

Calculate the total value of an object using Typescript

Here is the data that I have: [Products, Products, Products, Products] 0: Products {product_id: "1", Product_type_id: "11", Subtotal:450, …} 1: Products {product_id: "2", Product_type_id: "22", Subtotal:550, …} 2: Products {product_id: ...

Can you explain the functionality of this code snippet from a slate.js demonstration?

Trying to grasp the concepts of Slate.js, I delved into the rich text example. Within it, I encountered a code snippet that has left me puzzled. const isBlockActive = (editor, format) => { const [match] = Editor.nodes(editor, { match: n => ...

Ways to keep information hidden from users until they actively search for it

Currently, I have a custom filter search box that is functioning correctly. However, I want to modify it so that the data is hidden from the user until they perform a search. Can you provide any suggestions on how to achieve this? Below is the code I am u ...