Is it possible to implement pagination on a material table in Angular 10 without relying on the MatTableDataSource component?

How can I implement material pagination on a table without using MatTableDataSource? Most tutorials and examples I find online recommend the use of MatTableDataSource, but I'm unsure of how to actually utilize it. I am fetching data from a database table to populate my material table.

users: any[] = [];
displayData = [];
dataSource = [];
@ViewChild(MatPaginator) paginator: MatPaginator;

constructor(
    private authService: AuthService,
    private userService: UserService,
    private router: Router,
    private httpClient: HttpClient
  ) {}

  ngOnInit(): void {
    this._getUsers();
    
  }

private _getUsers() {
    this.userService;
    this.userService.getUsers().subscribe((data) => {
      this.users = data.users;
      this.displayData = data.users;      
      this.dataSource = this.users;
      
    });
<div class="users">
  <app-extend-table #usersTable
                       [header]="header"
                       [data]="displayData"
                       [columns]="columns">
  </app-extend-table>
  <!-- <mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator> -->
  
</div>

Answer №1

To display the corresponding items in a table, you should include

[length]="users?.length"
and listen for the output event of page from mat-pagination.

Here is an example:

<mat-paginator (page)="pageChanged($event)" [length]="users?.length" [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>

In the TypeScript file:

 // Import PageEvent from Angular Material pagination
pageChanged(event: PageEvent) {
const users = [...this.users];
   this.dataSource = users.splice((event.pageIndex - 1) * event.pageSize, event.pageSize );
}

For a working example, see: https://stackblitz.com/edit/angular-adrxts?file=app/table-pagination-example.ts

Answer №2

Here's a snippet of an update on the TS file

import { PageEvent } from '@angular/material/paginator';

@ViewChild(PageEvent, { static: false }) paginator: PageEvent;
displayData = [];
dataSource = [];
public list = new MatTableDataSource();
pageEvent: PageEvent;

constructor(
    private userService: UserService,
    private router: Router,
    private httpClient: HttpClient
  ) {}

  ngOnInit(): void {
    this._getUsers();    
  }

private _getUsers() {
    this.userService;
    this.userService.getUsers().subscribe((data) => {
      this.users = data.users;
      this.displayData = data.users;      
      this.dataSource = this.users;      
    });

pageChanged(event: PageEvent) {
    const list = this.users    
    console.log('list: ' + list);
    this.dataSource = list.splice((event.pageIndex - 1) * event.pageSize, event.pageSize);
    console.log(this.dataSource)
  }

Snippet from the HTML file

<div class="users">
  <app-extend-table #usersTable
                       [header]="header"
                       [data]="displayData"
                       [columns]="columns">
  </app-extend-table>
<!-- "users?.length" -->
  <mat-paginator (page)="pageChanged($event)"
               [length]=  "2"             
               [pageSizeOptions]="[2, 4, 6]"
               showFirstLastButtons>

</mat-paginator>
  
</div>

Component app-extend-table

ngAfterViewInit() {
    this.tableData.sort = this.sort;
  }

  ngOnInit(): void {
   
    this.columns.forEach((col) => {
      let pair = Object.entries(col);
      this.columnKeyValuePairs.push(pair[0]);
      this.displayedColumns.push(pair[0][0]);
    });
  }

  ngOnChanges(old) {
    if (old.data) {
      this.tableData = new MatTableDataSource<any>(old.data.currentValue);
      this.tableData.sort = this.sort;
    }
  }

Answer №3

Having encountered the same scenario, I tested @Ashot Aleqsanyan's solution and discovered a flaw. When using

this.dataSource = users.splice((event.pageIndex - 1) * event.pageSize, event.pageSize );
, it displays the same number of rows as the pageSize even on the last pageIndex.

For instance: if the selected pageSize is 5 and there are 6 data rows, ideally the first page should display 5 rows and the last page should show the remaining 1 row. However, it erroneously shows all 5 rows by repeating previous rows (2-5).

The issue was resolved by implementing

this.dataSource = new MatTableDataSource(rows.splice((event.pageIndex * event.pageSize), event.pageSize ));
.

Here is an operational example: https://stackblitz.com/edit/angular-adrxts-7npzwj?file=app%2Ftable-pagination-example.ts

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

Issue encountered during Angular upgrade from version 2 to 4 due to a mismatch in node versions

Encountering an error while trying to run npm start: ERROR in Cannot read property 'getSymbolByModule' of undefined. Checked the node version in cmd using node -v, resulted in V6.11.1, however, when executing ng-v cmd, got: angular-cli: 1.0.0-be ...

Declare the variable as a number, yet unexpectedly receive a NaN in the output

I'm facing an issue with a NaN error in my TypeScript code. I've defined a variable type as number and loop through an element to retrieve various balance amounts. These values are in the form of "$..." such as $10.00 and $20.00, so I use a repla ...

Difficulty with setting up Typescript in Visual Studio Code on MacOS Catalina

I'm currently facing an issue that appears to be related to the environment. How can I resolve it? And how do I link the installed TSC to my console? Steps to Recreate: npm install -g typescript was able to successfully install or update [email ...

Error in Angular FormGroup validation observed while conducting Cypress test

When the formGroup is invalid, a button is disabled. The button only becomes enabled if the conditions below are met: const field = this.formBuilder.group({ fieldType: new FormControl("", [Validators.required]), fieldName: new FormControl("", ...

Testing Angular combineLatest with Jest

I'm encountering a challenge in an assessment involving a complex Statement related to combineLatest. Here is the snippet of code: component: export class ErinnerungenErinnerungenComponent implements OnInit, OnDestroy { ... erinnerungen: Erinne ...

App that uses Angular 2 for real-time data refreshing

As a newcomer to Angular and Nodejs, I am venturing into the development of a MEAN stack cryptocurrency exchange application. My approach involves setting up a nodejs backend to retrieve the current exchange rate from an API and presenting it in the HTML. ...

Tips for testing an Angular service method that returns a JSON object

I have a service in Angular that processes JSON input and returns JSON output after some operations. My positive test case for this service is failing consistently. I suspect the reason for this failure might be: Expected Result : [ Object({ key: &apos ...

Issues with Angular2's CUSTOM_ELEMENTS_SCHEMA Syntax

Recently, I set up a minimal ng2 application using the ng2 cli. Within my AppModule, I included schema: [ CUSTOM_ELEMENTS_SCHEMA ]. Additionally, in the template for my AppComponent, I have used <row></row>. However, I'm encountering the f ...

Customizing table header sort icons in PrimeNG 15.4+: A step-by-step guide

The most recent update in PrimeNG brought about a change in the way sort icons are implemented. Previously, they used an i tag with CSS classes which could be customized easily using my company's icons: https://i.sstatic.net/f0Nrq.png However, the n ...

The services generated by OpenAPI Generator typescript-angular are experiencing failures

While utilizing version 2.4.26 of this OpenApi generator ("@openapitools/openapi-generator-cli": "^2.4.26"), I am encountering issues with Angular services (Angular Version 13.2.0). For example, the services are passing too many arguments to the Angular Ht ...

Encountering issue 404 in Tour of Heroes tutorial due to "angular-in-memory-web-api" integration

After following the Angular TOH tutorial (literally copy-pasted), I have reached part 6 and encountered an issue at this step: Refresh the browser. The hero data should successfully load from the mock server. Unfortunately, the data does not load and I ...

What is the process for incorporating a third-party library into Angular 6?

Many developers face the challenge of using external libraries in Angular that are not officially supported, such as Clappr and HashWords. The desire is to integrate these libraries seamlessly into an Angular project, almost treating them like native Ang ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

The type 'Dispatch<any>' cannot be assigned to the type '() => null'. Error code: ts(2322)

While working on my application context, I encountered a typescript error: 'Type 'Dispatch' is not assignable to type '() => null'.ts(2322)'. I am fairly new to typescript and struggling to understand this error. Below is ...

Issue with ngx-bootstrap custom typeahead feature malfunctioning

I'm facing an issue while trying to develop a customized typeahead feature that is supposed to search my API every time the user inputs something, but it's not functioning as expected. The autocomplete() function isn't even getting accessed. ...

Idiosyncratic TypeScript behavior: Extending a class with comparable namespace structure

Lately, I've been working on creating a type library for a JavaScript written library. As I was defining all the namespaces, classes, and interfaces, I encountered an error TS2417 with some of the classes. I double-checked for any issues with method o ...

determine the appropriate month for the calendar month component based on the route selected

I have developed a calendar component where I want to preselect the default month based on the route parameters received for the component. Here is the calendar: <p-calendar [maxDate]="dateTime" [(ngModel)]="selectedMonth" name=&quo ...

The React Native Flatlist encountered an error due to a mismatch in function overloads

I'm currently working on a React Native app using Typescript, and I've encountered an issue with the Flatlist renderItem function. As someone who is new to both Typescript and React Native, I received the following error message: No overload ma ...

Resetting the value of a radio button input option to null using Angular2 ngModel

In my Angular2 application, I am attempting to implement radio button inputs using ngModel and value. The goal is to have three options: true, false, and null. However, I am struggling to assign a value of null to one of the inputs. Ideally, when nothing ...

What is the reason behind the absence of a hide/show column feature in the Kendo Grid for Angular?

In my Angular application, I have implemented a Kendo Grid for Angular with the columnMenu feature enabled. This feature allows users to hide/show columns from a popup: https://i.sstatic.net/B5VXo.png Surprisingly, upon checking the ColumnMenu documentat ...