When moving to the next page in server-side pagination, the checkbox remains unchecked

I have encountered an issue with my checkbox. When I navigate to the next page in server-side pagination and then return, the checkbox becomes unchecked.

I need to extend the object to include the checked field. How can I accomplish this?

Currently, the object is retrieved from the server using http.get.

If the Items objects include a checked field, I can utilize a new method that automatically checks the checkbox when returning to the site.

HttpService:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Items } from './items';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';

@Injectable()
export class HttpService {

  constructor(private http: HttpClient) {}

  private url: string = 'url-link';

  getItems(page: number, pageSize: number): Observable<Items> {
    const start = (page - 1) * pageSize;
    return this.http.get<Items>(`${this.url}/${start}/${pageSize}`);
  }
}

app.component.ts :

import { Component, OnInit } from '@angular/core';
import { HttpService } from './http.service';
import { Items } from './items';
import { List } from './list';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  private items = new Items();
  private checkItem: List[] = [];
  private pageSize: number = 10;
  private p: number = 1;

  constructor(private httpService: HttpService) { }

  ngOnInit(): void {
    this.getItems(1, this.pageSize);
  }

  private getItems(event: number, pageSize: number) {
    pageSize = this.pageSize;
    this.p = event;
    this.httpService.getItems(event, pageSize).subscribe(items => this.items = items);
  }

  private getItemFromCheckbox(item: List, event) {
    const index = this.checkItem.findIndex(newItem => newItem.id === item.id);
    if(event.target.checked) {
      if(index === -1) {
        this.checkItem.push(item);
      }
    }
    else {
      if(index !== -1) {
        this.checkItem.splice(index, 1);
      }
    }
    console.log(this.checkItem);
  }

  private sortItems(sortBy: string) {
    this.items.list.sort((a: List, b: List) => {
      if (sortBy === 'id-up') {
        if (a.id < b.id) {
          return -1;
        }
        else if (a.id > b.id) {
          return 1;
        }
      }
      else if (sortBy === 'id-down') {
        if (a.id < b.id) {
          return 1;
        }
        else if (a.id > b.id) {
          return -1;
        }
      }
      // Repeat for other fields like name, type, version
    });
  }
}

app.component.html :

<tr *ngFor="let item of items.list | paginate : { id: 'server', itemsPerPage: pageSize, currentPage: p, totalItems: items.count }; let i = index">
    <th><input class="form-check" type="checkbox" id="checkbox_category_{{i}}" (change)="getItemFromCheckbox(item, $event)" mdbDeepDirective></th>
    <th scope="row">{{item.id}}</th>
    <td>{{item.name}}</td>
    <td>{{item.type}}</td>
    <td>{{item.version}}</td>
</tr>

Answer №1

Upon reviewing the options, I have found the following:

Here is the object retrieved from the server:

{ 
   "count":124, 
   "list": 
          [ 
            {"type":"test","id":1,"name":"ddfgd","version":1}, 
            {"type":"test","id":2,"name":"dfgd","version":1},
            {"type":"test","id":4,"name":"dfgd","version":1} 
          ] 
}

You are already familiar with your Item()-class. To enhance the model locally, add the 'checked' field.

export class Item {
  constructor(
     public id: number,
     public name: string,
     public type: string,
     public version: string,
     public checked: boolean
  ){}
}

Declare your item list as follows:

private checkItem: Array<Item> = [];

Expand your Paging method:

private getItems(event: number, pageSize: number) {
    pageSize = this.pageSize;
    this.p = event;
    this.httpService.getItems(event, pageSize).subscribe(items =>

    {
       // Iterate through the list of items and check for matches in your
       // list of checked items. If a match is found, update the value.
       items.list.forEach(el => {
         for(let chItem of checkItem){
           if(el.id === chItem.id){
              el.checked = true;
              break;
         }

         if(!el.checked) {
             el.checked = false;
         }

       });

       // Update the lists accordingly.
       this.items = items;

     });
}

Now you can bind the checked directive to this field

<input class="form-check" type="checkbox" 
[checked]="item.checked" id="checkbox_category_{{i}}" 
 (change)="getItemFromCheckbox(item, $event)" mdbDeepDirective>

Implementing this should meet your requirements.

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

The data type 'void | Observable<any>' cannot be assigned to the type 'ObservableInput<any>'. Specifically, the type 'void' cannot be assigned to 'ObservableInput<any>'

I encountered an error in my visual studio code: Argument of type '(query: string) => void | Observable' is not assignable to parameter of type '(value: string, index: number) => ObservableInput'. Type 'void | Observable& ...

How can the Calendar Ant Design showcase events that have fluctuating dates?

Seeking a solution to display events on an Ant Design Calendar using dateCellRender with dates stored in a variable object. Here's an example of the object: [ { "id": 1, "content": "Example", & ...

In TypeScript, combining the numbers 0 and 1 results in the value 01

I am in the process of developing a Shopping Card feature. private _card: Map<Product, number> = new Map<Product, number>(); ... addToCard(prod: Product, amount: number = 1): void { const totalAmount: number = this._card.get(prod) + amou ...

Oops! There was an error: Unable to find a solution for all the parameters needed by CountdownComponent: (?)

I'm currently working on creating a simple countdown component for my app but I keep encountering an error when I try to run it using ng serve. I would really appreciate some assistance as I am stuck. app.module.ts import { BrowserModule } from &apo ...

Utilizing a TypeScript Variable as a Tagname in an HTML File within Angular

This specific problem is originally documented in this post. Despite being flagged as a duplicate, my scenario differs because the HTML content at hand is too extensive for utilizing innerHTML. The structure of my component's HTML file is as follows: ...

What is the method for defining a constant data type with a class property data type in typescript?

I've been working on developing a nestjs API and have been using classes to define my entities. For instance, I have created a Customer entity as shown below: export class Customer { id: number; name: string; } Now, while working on my Custom ...

The term 'App' is being referenced as a value when it is intended to be a type. Perhaps you meant 'typeof App'?

I am eager to master Typescript with React through hands-on experience, so I recently made the manual transition from JavaScript to TypeScript in my create-react-app. However, when working with my default testing file App.test.ts: import { render, screen ...

I am looking to dynamically assign CSS classes to elements in my HTML document. Additionally, my project utilizes Angular 5 and Bootstrap version 3.3.7

I am currently in the process of generating a table using data obtained from a JSON. Due to the potential for a large amount of data, I have implemented a loop to create all the rows within the table. My goal is to enable users to click on any specific row ...

Utilize the .mat-column-name attributes to apply custom styles to a nested component within Angular Material

Within the Child component, an Angular material table is created with columns passed as input: <table mat-table> <ng-container *ngFor="let col of columns" [matColumnDef]="col"> </table> @Input() columns: string[] T ...

Issue: MUI Autocomplete and react-hook-form failing to show the chosen option when using retrieved information

The MUI Autocomplete within a form built using react hook form is causing an issue. While filling out the form, everything works as expected. However, when trying to display the form with pre-fetched data, the Autocomplete only shows the selected option af ...

Angular: Safely preserving lengthy content without the use of a database

As a beginner working on an Angular 11 educational website with approximately 20 static articles, I created a component template for the articles to receive text inputs. However, I am wondering if there is a more efficient way to handle this. Is there a ...

Color key in square shape for graph legend

I am looking for legend colors in square shape, but I don't want them to appear as square boxes on the graph. https://i.stack.imgur.com/Of0AM.png The squares are also showing up on the graph, which is not what I want. https://i.stack.imgur.com/Az9G ...

Error in React Native Navigation: Passing parameters is not functioning properly

Within my React Native application, I have meticulously established the following routes in my app.js: export default class App extends Component { render() { return ( <NavigationContainer> <Stack.Navigator initialRouteName=&qu ...

The menu's mouseover event is activated when hovering over the inner element

Whenever a user hovers over a specific element, a menu appears. This menu remains visible only as long as the user is hovering over it. However, the issue arises when there are elements within the menu itself, causing the menu to hide when the user hovers ...

transmit URL parameters to Express using Angular 2

I have implemented an Angular service to retrieve data from Express: getRestaurants(districtId) : Observable<void[]>{ let params: URLSearchParams = new URLSearchParams(); params.set('id', districtId); return this.http.get(this.url, ...

Creating validation rules for a form that includes a From Date and a To Date

Looking to implement validation for the from date and to date fields within a template-driven form. Is there a way to ensure that the "from date" is always greater than the "to date," and vice versa? Additionally, I would like to find a way to reuse this ...

The function in Angular 2 is invoked a total of four times

Take a look at this example. This example is derived from an Angular quick start sample, where the template invokes a function. import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: `<h1>Hell ...

Modify visibility or enable state of a text box according to a checkbox in PHP

Currently, I am utilizing PHP to exhibit a vertical list of numbered checkboxes, with one checkbox for each day in a specific month. Next to every checkbox, there is a text box where users can input optional notes for the selected day. To ensure that users ...

Using TypeScript - Implementing a generic constraint to allow passing a Zod schema result as an argument to a function

I'm in the process of creating a custom controller function to streamline my application. The repetitive task of wrapping try-catch, parsing a zod schema, and merging the request zod schema into a single object is present in all handler functions. The ...

The color syntax in the text editor of Visual Studio 2022 is being lost when casting an interface

After attempting to cast an interface, the entire code turns white. let object : someInterface = <someInterface> someUnknownHapiRequestPayload View a screenshot of the text editor here I have already tried common troubleshooting steps such as updat ...