Upon initial loading, the Angular 7 variable in the view fails to initialize from the URL query parameters

I'm a newcomer to Angular and facing an issue with passing parameters from the URL to the view on initial load.

My URL contains a parameter called page:

.../catalog?page=3

In my component, I have the following code:

export class CatalogListComponent implements OnInit {
     page;

     constructor(private route: ActivatedRoute){
     }

     ngOnInit(){
       this.route.queryParams.subscribe(params => {
          this.page = +params['page'] || 1;
        });
     }

     setPage(page: number) {
    this.router.navigate(['catalog'], { queryParams: {...this.queryParams, page } });
  }
}

In the view, I am utilizing ngb-pagination:

<ngb-pagination class="pagination"
                              [collectionSize]="items.total"
                              [rotate]="true"
                              [(page)]="page"
                              [maxSize]="5"
                              [pageSize]="20"
                              (pageChange)="setPage(page)"
              >
</ngb-pagination>

Whenever I open or refresh the link in the browser .../catalog?page=3, ngb-pagination always displays page 1 instead of 3, even though subsequent navigation works correctly (the page number in the URL and pagination matches).

What could be the mistake that I am making?

Answer №1

Previously mentioned, it is advisable to optimize your function using the provided code snippet:

 loadUserData(){
       this.apiService.getUserData().subscribe(data => {
          this.userData = data;
        });
     }

Additionally, a helpful tip to display desired information in the console:

console.log('The value I need is: ', example);

Answer №2

<ngb-pagination [collectionSize]="total | async" 
(pageChange)="updatePage($event)"  
[(page)]="currentPage" aria-label="Pagination"></ngb-pagination>

Make sure to pass the $event as an argument for the page change event handler

Reference: http://plnkr.co/edit/TDm5rv4RmxIKoWYWp8Qa?p=preview

Answer №3

To include the *ngIf directive as an attribute for ngb-pagination, the following code snippet should be added:

<ngb-pagination *ngIf="total" [collectionSize]="total"...></ngb-pagination>

This solution successfully resolved my issue.

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

Having trouble decoding a cookie received from a React.js front-end on an Express server

When using React js for my front end, I decided to set a cookie using the react-cookie package. After confirming that the request cookie is successfully being set, I moved on to configure the Express server with the cookie parser middleware. app.use(cookie ...

Combining the output of two Observables through the CombineLatest method to generate a

I possess two separate collections of information: Data Model: taxControlReference [ { "providerId": "HE", "taxTables": { "STAT": [ 1 ] } }, ...

What is the alternative method for reading an HTML text file in JavaScript without utilizing the input type file?

Within the assets folder, there is a text file containing HTML that needs to be displayed within a specific component's div. Is it possible to retrieve the contents of this file and assign them to a string variable during the ngOnInit lifecycle hook ...

Sending data to a component through event binding

I am currently working on an angular project where I am looking to display a series of buttons. When each button is clicked, I want it to display the corresponding button number. Is there a way to pass a specific value in the event binding that can be use ...

Control the contents of the DOM using JavaScript in a single-page application

Is there a way to append a div element with p and h3 tags after the <product-list> component in Angular? When I try putting it inside window.onload(), it only works when the page is reloaded or refreshed. This approach doesn't work well in singl ...

Angular 9 Server-Side Rendering Issue - ReferenceError: document is not defined Error Occurred

ERROR ReferenceError: document is not defined import { readFileSync } from 'fs'; const domino = require('domino'); // import the library `domino` const DIST_FOLDER = join(process.cwd(), 'dist/browser'); const t ...

Executing functions from a child component in a parent component in Angular 2

I'm currently working on ng2 RC6. I have a parent component and a child component. Within the child component, I am utilizing an ng2-bootstrap modal and the following start function: import { Component, ViewChild, AfterViewInit, Input } from '@ ...

Typescript - Identifying child type based on the specified property in keyof

I'm exploring the possibility of enhancing an interface by adding extra options to it. For example: interface IRole { id: number; name: string; } interface IAddress { line1: string; line2: string; city: string; state: string; zip: strin ...

Implementing a unique sorting algorithm for an array of numbers in Angular

I need to organize an array of numbers in descending order with a custom sorting method based on a specified number, all without splitting or filtering the array. I am currently working with Angular 17 and Rxjs 7.8. For instance, if I have this array of n ...

The npm crash is caused by Firestore addDoc

My approach to importing firestore looks like this: import { getFirestore, addDoc } from "firebase/firestore"; However, it seems to be causing issues with npm running my react app as it gets stuck during compilation and eventually shows the foll ...

Tips for properly typing action creators connected to properties in react-redux

Within our project, all action creators are structured in the following manner: export const actionCreatorFunctionName(arg1, arg2...) { return (dispatch: Dispatch, getStore: () => StoreState) => { // ... function logic ... dispat ...

Only object types can be used to create rest types. Error: ts(2700)

As I work on developing a custom input component for my project, I am encountering an issue unlike the smooth creation of the custom button component: Button Component (smooth operation) export type ButtonProps = { color: 'default' | 'pr ...

Missing expected property in TypeScript casting operation

I recently came across this intriguing playground example outlining a scenario where I attempted to convert an object literal into an object with specific properties, but encountered unexpected results. class X { y: string; get hi(): string { ...

The functionality of the Angular click event binding seems to be malfunctioning

When I click on a radio button, I want to see relevant selections. Below are the files: app.component.html <div class="col-md-3"> <b>Select Category</b><br> <input type="radio" name="colors" [(ngModel)]="typing" (clic ...

Troubleshooting a CSS problem within mat-autocomplete component in Angular 7

While using mat-autocomplete, I noticed that when I select an option from the dropdown and then scroll through the main bar, the dropdown menu does not move along with the autocomplete input field. view image here Here is the code snippet: <td width ...

The number type in Typescript is incompatible with the string type and cannot be assigned

Currently, I am deeply involved in developing a currency formatting directive for my Angular 4 application. In the parsing process, I am stripping out all characters except digits and decimal points to convert the input into a float number. However, I ne ...

Ways to effectively update the state through different methods

Defining the state in React as follows: export interface IRoleState { data: API.InterviewList, menus: API.MenuItem, meta: { total: number per_page: number page: number } } When receiving a response from the server, ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

The getMonthlyBalances function is providing inaccurate results when calculating stock balances

One of my functions is called getMonthlyBalances, which takes in two arrays - stocks and trades. It calculates the monthly balance of a user's stock holdings based on their trade history. The stocks array includes objects with stock ID, prices, and da ...

Effortlessly transfer model data to a different component in Angular upon clicking a button

Component A displays a list of Products, each with an option to view the details. When this option is clicked, I want Component B to show a list of items associated with that specific Product. I am having trouble passing the selected Product from Componen ...