By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – Angular Previous page button getting disabled when the next page button gets clicked
JavaScript

Javascript – Angular Previous page button getting disabled when the next page button gets clicked

Admin
Last updated: 2023/12/11 at 4:17 PM
Admin
Share
4 Min Read
Angular Previous page button getting disabled when the next page button gets clicked

Problem:

Hi I am new to angular and I am trying to implement pagination in my api and ui both I have tested and integrated the pagination in my api but bot able to implement pagination correctly in my UI. So I am stuck when I am clicking on next page button I am not able to navigate to my previous page and on first page it shows 1/2 (dealing with a db with only 2 entries right now) but when I click on next page it shows 1/1 and the next record loads and my previous button gets disabled.

Contents
Problem:Solution:

This is my html file

<mat-paginator #paginator
   (page)="loadPage($event)"
   [length]="length"
   [pageSize]="pageSize"
   [disabled]="disabled" 
   [showFirstLastButtons]="showFirstLastButtons"
   [pageSizeOptions]="showPageSizeOptions ? pageSizeOptions : []"
   [hidePageSize]="hidePageSize"
   [pageIndex]="currentPage"
   aria-label="Select page">
</mat-paginator>

This is my component.ts file

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { NewPatientComponent } from 'src/app/core/dialogs/new-patient/new-patient.component';
import { PatientVisitComponent } from 'src/app/core/dialogs/patient-visit/patient-visit.component';
import { PatientService } from 'src/app/core/service/patient/patient.service';
import { AbhaRegistrationComponent } from '../abha-registration/abha-registration.component';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';

@Component({
  selector: 'app-patient',
  templateUrl: './patient.component.html',
  styleUrls: ['./patient.component.css'],
})
export class PatientComponent implements AfterViewInit {
  pageSize = 1;
  length = 0;
  pageIndex = 0;
  pageSizeOptions = [5, 10, 25];
  currentPage = 0;

  hidePageSize = false;
  showPageSizeOptions = true;
  showFirstLastButtons = true;
  disabled = false;

  tableColumns: string[] = ['id', 'name', 'address', 'dateOfBirth', 'actions'];
  selectedPatient: any;
  public dataSource = new MatTableDataSource<any>([]);

  @ViewChild(MatPaginator) private paginator: MatPaginator;

  constructor(
    private dialog: MatDialog,
    private patientService: PatientService,
    private router: Router,
    private route: ActivatedRoute
  ) {}

  ngAfterViewInit(): void {
    this.getAllPatients();
    this.dataSource.paginator = this.paginator;
  }

  loadPage(event: PageEvent): void {
    if (event.pageIndex > this.currentPage) {
      // Navigating to the next page
      this.currentPage = event.pageIndex;
    } else if (event.pageIndex < this.currentPage) {
      // Navigating to the previous page
      this.currentPage = event.pageIndex;
    }

    this.pageSize = event.pageSize;
    this.getAllPatients();
  }

  getAllPatients() {
    this.patientService
      .getAllPatients(this.currentPage, this.pageSize)
      .subscribe(
        (res) => {
          if (res && res.content) {
            this.dataSource.data = res.content;
            this.length = res.totalElements;
          } else {
            console.error('API response is missing expected data:', res);
          }
        },
        (err) => {
          console.error('Error getting patients:', err);
        }
      );
  }

  newPatientDialog() {
    this.dialog.open(NewPatientComponent).afterClosed().subscribe((res) => {
      this.getAllPatients();
    });
  }

  openVisitDialog(patient: any) {
    this.dialog.open(PatientVisitComponent, {
      data: patient,
    });
  }

  openAbhaDialog(patient: any) {
    this.router.navigateByUrl('/abha', { state: patient });
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value.trim().toLowerCase();
    this.dataSource.filter = filterValue;
    this.dataSource.filterPredicate = this.customFilterPredicate();
  }

  customFilterPredicate() {
    return (data: any, filter: string) => {
      const name = `${data.firstName} `.toLowerCase();
      return name.includes(filter);
    };
  }
}

Solution:

Hard to say, what goes wrong without knowing backend side. But maybe I can give you a hint, that may solve your problem.

When switching pages you call loadPage() and in there you call getAllPatients(). There you are setting this.length = res.totalElements;. Are you sure that your API response for totalElements is NOT 1 on your second page? I suppose this would result in only having one page left on your paginator.

Offtopic:
In loadPage() instead of

   if (event.pageIndex > this.currentPage) {
      // Navigating to the next page
      this.currentPage = event.pageIndex;
    } else if (event.pageIndex < this.currentPage) {
      // Navigating to the previous page
      this.currentPage = event.pageIndex;
    }

you can just write this.currentPage = event.pageIndex;. The if/else statement is senseless here.

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Find available time slots between events with Google Calendar API in js Javascript – Find available time slots between events with Google Calendar API in js
Next Article Conditionally Show HTML with JavaScript After Input Checkbox Is Checked Javascript – Conditionally Show HTML with JavaScript After Input Checkbox Is Checked
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?