Steps for building a personalized pipe to paginate data within Angular

Creating a custom pagination pipe in Angular to filter data and display 100 records per page. For example, page 1 shows records 0-99, page 2 shows records 100-199, and so on.

The data.json file contains an array with 1300 objects. Sample data: https://pastebin.com/7V2DNj8W

Each object in the data looks like this:

{
    "location_type": "KAUPPAKESKUS",
    "postalcode": "2770",
    "availability": "24 H AUKIOLO",
    "location": "ESPOONTORI /INSTRUMENTARIUM",
    "municipality": "ESPOO",
    "target_address": "KAMREERINTIE 3",
    "availability_details": "",
    "coordinates_lon": "24.656450",
    "coordinates_lat": "60.203750"
}

The pagination.pipe.ts code snippet ensures that the correct records are displayed on each page based on the provided parameters.

// Code snippet omitted for brevity

When navigating to different URLs such as http://localhost:4200/page/0 and http://localhost:4200/page/1, the expected records should be displayed in the console and in the corresponding table.

Correction:

This is the content of page.component.html:

// Code snippet omitted for brevity

and here is page.component.ts:

// Code snippet omitted for brevity

Answer №1

There appears to be a potential issue with the "index" logic.

let index = 0;

...

if (index >= (page * per_page) && index < (page + 1) * per_page) {

If the index consistently remains at zero, then- page 0:

if (0 >= (0 * 100) && 0 < (0 + 1) * 100) // true, list will be generated

page 1:

if (0 >= (1 * 100) && 0 < (1 + 1) * 100) // false, (0 >= (1 * 100) will never evaluate to true

pages greater than 1:

// outcome will be similar to page 1

You may consider setting your index to begin at page * page_size - 1

Answer №2

The main issue at hand is that the variable page is currently defined as a type of string instead of number. This causes an error in the calculation of the expression when the value of page is 1, resulting in an incorrect output:

let lastIndex = page + 1 // displays 11 instead of 2

To resolve this issue, I updated the variable page to be of type number as follows:

ngOnInit() {
    this.route.params.subscribe(parameters => {
        this.page = +parameters.page;
    })
}

Additionally, the statement index++ must be placed outside of the if condition within the loop to ensure that the index is incremented with each iteration:

for (let atm of atms) {
  if (index >= (page * per_page) && index < (page + 1) * per_page) {
    data.push(atm);
  }
  index++;
}

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

How do I set class properties in TypeScript using an array of values for initialization?

My constructor has the following structure: constructor(values: Object = {}) { //Constructor initialization Object.assign(this, values); } However, it currently requires named initialization like this : new Inventory({ Name: "Test", ...

Is it possible in Typescript to reference type variables within another type variable?

Currently, I am working with two generic types - Client<T> and MockClient<T>. Now, I want to introduce a third generic type called Mocked<C extends Client>. This new type should be a specialized version of MockClient that corresponds to a ...

Angular: Object contains data, but its properties have not been defined

I am encountering an issue while trying to access properties of the Dto object filled from my rest service, as they are coming up undefined. Firstly, I fetch the data: this.mapservice.getAllCoordinates().subscribe((data: CoordinateDto[]) => { this.co ...

Hostlistener is unresponsive to inputs from arrow keys

Within my Angular 2 component, I have implemented a key event listener to capture keystrokes: @HostListener('document:keypress', ['$event']) handleKeyboardEvent(event: KeyboardEvent) { console.log(event); } Oddly enough, I am not ...

Merge different JSON files to generate a new JSON file

I am faced with a challenge involving 2 separate JSON files. Here is the content of each: User.json: { "users": [ { "username": "User1", "app": "Git", "role": "Manager" }, ...

Enhancing validation in Express with custom Typescript types for validation in Express Validator

I encountered an error while using the custom method of the express validator Issue: Argument of type '(userDoc: User | null) => Promise<never> | undefined' is not assignable to parameter of type '(value: User | null) => Promise ...

How to optimize and reduce bundle size in Webpack using tree-shaking, babel-loader, TypeScript tsconfig target configuration, @babel/preset-env with modules set to false, and setting side

Looking to implement the tree-shaking feature of Webpack for es6-modules or ESM (.ejs)? Here's a detailed breakdown: My goal is to configure tree-shaking with Webpack v5 using babel-loader (adjustable from webpack.*.config.js), Babel v7 with @babel ...

When utilizing the HTML5 range input type, the value of 'this.value' may not be defined

I'm having an issue with a range input where it returns undefined when passed to my function: Here is the HTML code snippet: <div class="slidecontainer"> <label>Setpoint</label> <p>{{channel.setPoint}}</p> & ...

Struggling to utilize a custom react-three-fiber component despite specifying the custom type within the react-three-fiber module

Currently developing a react application focused on visualizing mathematical concepts with the help of react-three-fiber. Utilizing TypeScript, I discovered that by extending custom ThreeElements (https://docs.pmnd.rs/react-three-fiber/tutorials/typescript ...

Guide on transforming absolute imports into relative imports using Rollup.js?

Currently in the process of reorganizing my code and rewriting some TypeScript modules that are anticipated to be utilized by multiple microservices as packages. Encountering an issue with absolute imports enabled by baseUrl in relation to this package co ...

Discover the secret to seamlessly observing data modifications between sibling components in Angular 5 without the need to refresh the entire page

I am facing an issue with two sibling components in my application. The first component includes a select box with different options that are bound to a variable called selectedValue. My goal is to have the value updated in the second component whenever it ...

Angular 4 - The bindings are restricted from having assignments within them

Looking to include a CSS selector as an @Input in my component. To achieve this, I need to use the following syntax for passing a css selector: <mds-datetime-picker [inLine]="true" [targetSelector]='[data-name="target"]'></mds-datet ...

Angular Material Select without underline not specified

I'm currently utilizing Angular Material for my project. My task involves creating a custom component that includes a md-select component. However, I'm facing an issue where the md-select component needs to have no underline, similar to a workaro ...

Learn how to update scope variables in Angular.io's mat-autocomplete using the [displayWith] function feature

I'm encountering a problem where I am unable to update locally declared variables in the component controller that triggers the mat-autocomplete. The issue is that these variables are confined within a specific scope, preventing me from making any mod ...

Encountering a TypeError in NextJS: "Uncaught window.fbq is not recognized as a function"

Trying to implement Facebook Pixel for event tracking on the client side within my NextJS app-router project. Following the instructions provided in the NextJS pixel repository: https://github.com/vercel/next.js/tree/canary/examples/with-facebook-pixel/ap ...

"Exploring the capabilities of Rxjs ReplaySubject and its usage with the

Is it possible to utilize the pairwise() method with a ReplaySubject instead of a BehaviorSubject when working with the first emitted value? Typically, with a BehaviorSubject, I can set the initial value in the constructor allowing pairwise() to function ...

Angular 11 - New Script Inserted into scripts Directory and Linked in angular.json Configuration

I just added a new script file in the src/assets/scripts directory and updated its path in the scripts section of angular.json. My question is: Will I need to restart ng serve for the changes to take effect the next time the application is run? Thank you ...

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

What is the Reason for TypeScript's Inability to Verify the Type of Dynamic Key Object Fields?

How come TypeScript allows the declaration of seta even though it doesn't return objects of type A? type A = { a: '123', b: '456' } // Returns copy of obj with obj[k] = '933' function seta<K extends keyof A> ...

I am facing an issue with calling a controller from an HTTP GET request in ASP.Net Core 6 using a Single Page Application (SPA) endpoint

[UNSOLVED] - Seeking help from developers [Issue] As a newcomer to the industry, I apologize for my lack of experience in advance. I am currently facing a challenge with ASP.Net Core 6 and it seems like I am missing something simple, but I can't see ...