How can one dynamically update a page in Angular when the path is changed?

I am facing a pagination issue in Angular. Here is my HTML code:

<!-- A div element for pagination part at the bottom of the page -->
<div style="margin-left: 50%; margin-top: 20px; margin-bottom: 20px">
    <ul class="pagination">
        <li class="page-item"><button class="page-link" (click)="selectedPage('Previous')">Previous</button></li>
        <li class="page-item" *ngFor="let p of page_num">
            <button class="page-link" (click)="selectedPage(p)" routerLink="/games/page/{{p}}">{{p}}</button>
        </li>
        <li class="page-item"><button class="page-link" (click)="selectedPage('Next')">Next</button></li>
    </ul>
</div>

Explanation is that this code sends the clicked page number to my TypeScript file containing this piece of code:

/*Created an element called currentPage to get the current page and send it to getGames func (my subscribe func), this element will be dynamically change, but will start from 1*/
  currentPage = 1;
  //Created a page_num cevtor that will be change when page selected
  page_num : number[] = [this.currentPage, this.currentPage+1, this.currentPage+2];

    //Created a func called selectedPage in order to adjust the page numbers and send corretc page num to funcs, all the data I am using is sotred in a vector called gamesVector
      public selectedPage(page) {
        //If clicked option was 'Previous'
        if(page == 'Previous') {
          //If previous of that page is not null
          if(this.gamesVector.previous !== null) {
            this.currentPage--;
            this.page_num = [this.currentPage, this.currentPage+1, this.currentPage+2];
            this.router.navigate(['/games/page/' + this.currentPage])
          }
          else
            alert('You are already in the first page')
        }
        //If clicked option was 'Next'
        else if(page == 'Next') {
          //If next of that page is not null
          if(this.gamesVector.next !== null) {
            this.currentPage++;
            this.page_num = [this.currentPage, this.currentPage+1, this.currentPage+2];
            this.router.navigate(['/games/page/' + this.currentPage])
          }
          else  
            alert('You are already in the last page')
        }
        //If the clicked option was a page number
        else {
          this.currentPage = page;
          this.page_num = [this.currentPage, this.currentPage+1, this.currentPage+2];
        }
    
        //Then call the games subscribe function with the new page number, so the games can be refreshed
        this.gameAndCatServ.getGames(this.currentPage).subscribe(data => {
          this.gamesVector = data;
        })
    
        //To scroll all the way up when changing the page
        window.scrollTo(0, 0)
      }

The functionality works well, but there are issues when the page number is changed directly from the URL or by using the browser's back button. How can I ensure that the page refreshes in such scenarios?

Answer №1

Suppose you have a URL path like this:

To make sure changes to the path are reflected, utilize "queryParameters" from Angular ActivatedRoute. Here's an easy example:

import { ActivatedRoute } from '@angular/router';

constructor(
    private readonly route: ActivatedRoute,
  ) {}

ngOnInit(): void {
  this.route.queryParams.subscribe(queryParams => {
    this.currentPage = !!queryParams['page'] ? queryParams['page'] : 1;
  });
}

Now, enjoy having two-way bindings for pagination using query parameters.

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

Error in cypress configuration occurs when a plug is mistakenly defined as an import instead of a const within the cypress.config.ts file

Hello, I am new to using Cypress so please bear with me if this seems like a trivial issue. Below you will find my cypress.config.ts file where I am attempting to integrate the cypress esbuild preprocessor into the configuration. import cypress_esbuild_pre ...

Is there a way to remove a dynamically rendered component from a list?

Whenever I click a button, the same component is dynamically rendered on top of the list. But now, I need to implement a feature where users can delete any component from the list by clicking a cancel button associated with each component. Here's my ...

Establishing default parameters for angular pipes

Is there a way to establish default settings for an angular pipe without creating a custom one myself? I frequently utilize the currency pipe in this manner {{ price | currency:'EUR':'symbol':'0.2-2':'de' }} I&apo ...

Examples or links pertaining to the tabs bar in Ionic

Is there a specialized tutorial or example available for finding non-default tabs in Ionic 5? I'm looking for alternatives to the default tabs and would appreciate any help in the form of links, examples, or tutorials. Thanks in advance! https://i.ss ...

What causes the "node: bad option" error to occur when I include a custom flag in the nodejs command line within an Angular 9 application?

Seeking assistance with adding a custom flag to the npm start command in an Angular 9 project. The goal is to intercept proxy requests within the local server and manipulate data. However, encountering the "node: bad option" error consistently. Looking for ...

ng-module with tabbed content

I am facing a unique scenario where I have a UserProfileComponent with a tab structure and I want to add tabs from different modules. UserProfileComponent.html <ngb-tabset> <ngb-tab> <app-user-profile-history></app-user-prof ...

The issue with Angular 2's Parameterised router link component not fully refreshing

I'm trying to figure out how to show a set of images when I click on a specific menu item. The menu structure looks like this: <ul id="demo23" class="collapse"> <li> <a [routerLink]="['image-gallery','Picasso ...

The Primeng badge feature fails to detect changes in severity

Within my primeng application, there is an icon featuring a badge that is structured as follows: <i (click)="showAllNotifications()" class="pi pi-bell mr-3 p-text-secondary" pBadge style="font-size: 2rem" [value]=&q ...

The [image link] in the NextJS image was loaded in advance using link preload, but it was not utilized within a short time after the window finished loading

While working on my blog website with NextJS, I encountered a warning in the console related to using next/image: The resource http://localhost:3000/_next/image... was preloaded using link preload but not used within a few seconds from the window's lo ...

Using class-validator in Node.js to validate arrays of objects

My goal is to verify the Alcohol ID and Alcohol Name for emptiness. Below is the format I am working with: { "barId": "string", "barName": "string", "drinksItems": [ { "alcoholId": "string", "alcoholName": "string", "mixerLis ...

Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property. let arrayA = ...

Is implementing client components in Server Side pages an effective strategy for optimizing SSR performance?

In order to overcome the challenge of using client-side components in server-side pages, I made the decision to create a client-side wrapper to encapsulate these components within server-side pages. This way, I can manage all API calls and data fetching on ...

React experimental is encountering an issue with missing property "" $fragmentRefs"" when relaying fragments

Details Recently, I decided to explore React experimental features with concurrent mode and relay. Even though I have never used relay before, I managed to make progress but ran into some issues. Initially, using the useLazyLoadQuery hook without any frag ...

Is there a ReactNode but with greater specificity?

In setting up the properties for a component, I have defined them as follows: interface HeaderProps{ title: string; image: string; link: ReactNode; } The 'link' property is meant to refer to another component, specifically <Link /> ...

When working with the "agora-rtc-sdk-ng" package, an error may be thrown by Next.js stating that "window is not defined"

Currently, I am in the process of incorporating the "agora-rtc-sdk-ng" package for live streaming with next.js and typescript. import AgoraRTC from 'agora-rtc-sdk-ng'; However, when I try to import it, an error is thrown as shown below: https:/ ...

The error message "Cannot bind to 'matDatepicker' because it is not recognized as a property of 'input'" is indicating an issue with Angular

After copying and pasting Angular material code for a datePicker and input, I encountered an error specifically related to the datePicker component. app.module import {MaterialModule} from '@angular/material'; @NgModule({ imports: [ ... Materia ...

Whenever I attempt to run the NPM install command in the Terminal, it seems to generate multiple errors

I am encountering an issue on my work laptop. I have the latest versions of Angular, Nodejs, Nodesass, and VScode installed in the local environment path. Whenever I download an Angular template from Github and try to do NPM Install, it consistently thro ...

Exploring JSON object nesting

I need to extract specific objects (fname, lname, etc.) from the data received in node.js from an Angular front-end. { body: { some: { fname: 'Fuser', lname: 'Luser', userName: 'userDEMO', pas ...

Defining Objects in TypeScript

Within my TypeScript application, I currently have the following code: interface Data { url: string, // more stuff } (...) export class something() { public data: Data; } method(){ this.data.url = "things"; } However, every time I atte ...

Can deferrable views function solely within independent components?

Experimenting with deferrable views, I have implemented the following code within a standard (NgModule-based) component. @defer (on interaction) { <app-defer></app-defer> }@placeholder { <p>click to load</p> } The DeferComp ...