Pagination in PrimeNG datatable with checkbox selection

I am currently working on incorporating a data table layout with pagination that includes checkbox selection for the data. I have encountered an issue where I can select data on one page, but when I navigate to another page and select different data, the selection from the first page is lost.

Here is a snippet of the code:

    <p-dataTable [value]="cars" [rows]="10" [paginator]="true" [pageLinks]="3" [rowsPerPageOptions]="[5,10,20]" sortMode="multiple" [(selection)]="selectedCars2">
        <p-column [style]="{'width':'38px'}" selectionMode="multiple" ></p-column>
        <p-column field="vin" header="Vin"></p-column>
        <p-column field="year" header="Year"></p-column>
        <p-column field="brand" header="Brand"></p-column>
        <p-column field="color" header="Color">
            <template let-col let-car="rowData" pTemplate type="body">
                <span [style.color]="car[col.field]">{{car[col.field]}}</span>
            </template>
        </p-column>

        <!--<p-column styleClass="col-button">
            <template pTemplate type="header">
                <input type="checkbox" [(ngModel)]="checkUncheckAll" />
            </template>
            <template let-car="rowData" pTemplate type="body">
                <input type="checkbox" [(ngModel)]="checkValue[car.vin]" (click)="selectCar(car, checkValue[car.vin])"/>
            </template>
        </p-column>-->
    </p-dataTable>

    <div class="table-controls-top"><div class="pager"><input type="button" class="button_tablecontrol" (click)="selectCar(selectedCars2)" value="Delete"></div></div>

Additionally, here is an excerpt from the TypeScript file:

import {Component, OnInit} from '@angular/core';
import {Car} from '../domain/car';
import {CarService} from '../service/carservice';
import {Message} from '../common/api';

@Component({
    templateUrl: 'app/showcase/demo/datatable/datatabledemo.html'
})
export class DataTableDemo implements OnInit {

    cars: Car[];
    
    cols: any[];
    
    msgs: Message[] = [];
    
    checkValue: any;
    
    selectedCars2: any[];
    
    // Constructor
    constructor(private carService: CarService) {
        
        this.checkValue = {};
        
        this.selectedCars2 = [];
        
    }
    
    // Initialization method
    ngOnInit() {
        this.carService.getCarsCustom().then(
        cars => {
            this.cars = cars;
            for(var car of this.cars) {
            console.log(car.vin)
                this.checkValue[car.vin] = false;
            }
        });

        this.cols = [
            {field: 'vin', header: 'Vin'},
            {field: 'year', header: 'Year'},
            {field: 'brand', header: 'Brand'},
            {field: 'color', header: 'Color'}
        ];
    }

    selectCar(selectedCars) {
        
        console.log(selectedCars)
        console.log(this.selectedCars2)
    }

}

https://i.stack.imgur.com/TUkdV.png

It appears that the team has not yet implemented the functionality needed to retain row selections ('selectedCars2') with pagination. Any suggestions or insights on how to address this issue would be greatly appreciated.

Thank you in advance.

Answer №1

For a solution to this issue, head over to the discussion on github:

Handling DataTable selection with pagination

To provide immediate assistance:

HTML:

    <p-dataTable [value]="data" [rows]="PageSize" 
    [paginator]="ShowPaginator" [pageLinks]="3" [(selection)]="selectedData"
    (onHeaderCheckboxToggle)="onTableHeaderCheckboxToggle($event)">
           <p-column [style]="{'width':'38px'}" selectionMode="multiple"></p-column>
    </p-dataTable>

TS:

   class Test {
     private data: MyData[]; 
     selectedData: MyData[];

     onTableHeaderCheckboxToggle(event: any) {
      if (event.checked === true) {
         for (let m of this.data) {
            if (/* Implement your condition here if the element is not already in the array*/) {
               this.selectedData.push(m);
            }
         }
      } else {
         this.selectedData.length = 0;
      }
    }

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

Typescript is struggling to locate a module that was specified in the "paths" configuration

Within my React project, I have set up a module alias in the webpack config. Now, I am looking to transition to Typescript. // I have tried to simplify the setup as much as possible Here is my tsconfig.json located in the root directory: { "compilerOp ...

Choosing and Duplicating Text in Angular

I'm attempting to give the user the ability to select a paragraph and copy it by clicking a button. However, my current code is not working as expected. I initially tried importing directives but encountered errors, prompting me to try a different met ...

Modifying the text of a material UI button depending on a particular condition

I have a component that uses the Material UI button, and I need to change the text of the button based on a condition. If the order amount is 0, I want it to display "cancel", otherwise, it should show "refund". Can someone guide me on how to achieve thi ...

Oops! There was an error: Uncaught promise rejection: TypeError - Unable to access 'subscribe' property of null object (Ionic Angular)

I encountered an issue in my angular ionic project. When I log in, the first page displays the error "ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of null." However, upon reloading the page, the error disappears ...

Encountered Angular SSR Serve Error: NullInjectorError - StaticInjectorError in AppServerModule with the following reference:

While working on building an application with Angular's SSR and serving it, I encountered a specific error. All services and components have been properly injected. Error: ERROR Error [NullInjectorError]: StaticInjectorError(AppServerModule)[REQUEST] ...

Using Typescript to overload functions with varying first parameters

I am facing a scenario where I have a parent class that requires a method implementation with either one or two parameters depending on the child class. class MyClass { update(obj: HashMap); update(id: ID, obj: HashMap); update(objOrId: HashM ...

Unable to call a component's method from a different component in Angular 7

How can I call the toggleSidebar() method of the SidebarComponent from the HeaderComponent using the callToggleSidebarOnToggleSidebarBtn() method? I am encountering an error that I cannot comprehend. What is the correct way to use a method of one component ...

Troubleshooting an issue with a Typescript React component that is generating an error when using

I am in the process of implementing unit testing in a Typescript and React application. To start off, I have created a very basic component for simplicity's sake. import React from "react"; import ReactDOM from "react-dom"; type T ...

Share edited collection with Observer

The challenge Imagine creating an Angular service that needs to expose an Observable<number[]> to consumers: numbers: Observable<number[]>; Our requirements are: Receive the latest value upon subscription Receive the entire array every tim ...

The OR operator in TypeORM allows for more flexibility in querying multiple conditions

Is there any OR operator in TypeORM that I missed in the documentation or source code? I'm attempting to conduct a simple search using a repository. db.getRepository(MyModel).find({ name : "john", lastName: "doe" }) I am awar ...

The best location to place a main.scss file within an Angular 2 project

I'm wondering where the best place is to put a main.scss file so that it can be utilized by all components. I attempted to place the css in app.component.ts (root component), but the styles weren't being applied to one of my components. Issue Re ...

Encountering the "DevToolsActivePort file does not exist" error when executing Angular e2e tests via GitHub Actions

Currently delving into the world of GitHub actions, I am in the process of executing Angular e2e tests within a continuous integration workflow. Utilizing the basic project structure generated by the Angular CLI, I have primarily focused on adjusting the ...

Error in Radix UI encountered while attempting to use "react-accordion"

Trying to import the root component of a react accordion and then export it in my project with the name Accordion. However, I keep getting a type error that says Unsafe assignment of an `any` value. I've attempted to fix it by using the as keyword but ...

Managing conflicting versions of React in a component library created with Webpack and Storybook

My goal is to create a React component library on top of MUI using Storybook and TypeScript. Since Storybook is based on Webpack (which includes SASS files), I'm utilizing Webpack to build the bundle because TSC can't compile those files. Subsequ ...

What could be causing the issue of Vuejs 3.3 defineModel consistently returning undefined?

I am currently working with Nuxt version 3.5.1 and Vuejs version 3.3, however, I am encountering an issue where the defineModel macro always returns undefined. I am unsure why this is happening? <template> <input v-model="count"& ...

Creating a merged object from a split string array in TypeScript

I possess an array containing objects structured as follows; const arr1 = [ {"name": "System.Level" }, {"name": "System.Status" }, {"name": "System.Status:*" }, {"name": "System.Status:Rejected" }, {"name": "System.Status:Updated" } ] My object ...

Express: issue retrieving numbers from request body array

JavaScript / TypeScript Issue: export const updateSettings = catchErrors(async (req, res) => { console.log("updateSettings req.body: ", req.body) const { organizationId, formdata, updatedItems, updateQuota } = req.body; console.lo ...

Disabling aria-label enforcement for icon-buttons in Chakra UI Typescript

Having a Chakra UI icon button, I am facing an issue with the aria-label attribute. The IconButton is within an aria-hidden section in the tree; therefore, the label becomes redundant. If I try to remove the aria-label, TypeScript throws complaints as sho ...

Angular: Merge two Observables to create a single list and fetch the combined data

I am currently working on creating a function that returns an observable with a list, compiled from several observables. I feel like I am very close to finding the solution because the debugger stops right before displaying the list. Here is my code: ts t ...

Creating a specialized Typescript deep partial type for specific attributes

I have a challenge in writing a utility type that takes an object as a generic parameter and a union of strings to recursively make specific properties optional. While it may sound simple, I encountered an issue that I need assistance with. Here is the uti ...