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

Here is a guide on showcasing information obtained from ASP.NET API in Angular version 13

My goal is to fetch motorcycle data from a web API and showcase it in my Angular project. ASP.NET Framework Web API 4.7 Angular CLI: 13.3.7 Angular: 13.3.11 On the Web API end: Controller: [EnableCors(origins: "*", headers: "*", ...

The malfunctioning collapse feature in Bootstrap 4 sidebar within an Angular 6 application

I am trying to find a way to collapse and reopen the sidebar when clicking on a button. I have attempted to create a function to achieve this, but unfortunately it did not work as expected. Important: I need to collapse the sidebar without relying on jque ...

The spread operator seems to be malfunctioning whenever I incorporate tailwindcss into my code

Hi there! I hope you're doing well! I've come across a strange issue in Tailwindcss. When I close the scope of a component and try to use props like ...rest, the className doesn't function as expected. Here's an example: import { Butto ...

Having difficulty customizing Mui Accordion with Styled Utility implementation

I am having trouble overriding the CSS for an Accordion using Mui styled utility. I am trying to apply a custom CSS class, but there seems to be an underlying class that is causing issues in my code. Here is the Mui class snippet: <div class="MuiPa ...

What is the reason behind document.body not being recognized as an HTMLBodyElement?

Why does Visual Studio suggest that document.body is an HTMLElement instead of an HTMLBodyElement? I've searched for an answer without success. class Test { documentBody1: HTMLBodyElement; documentBody2: HTMLElement; cons ...

Multiple ngFor loops causing only the final item to be displayed in the inner loop

Can someone assist with my code where I loop through firebase RTDB reference to retrieve a list and then use those results in a subsequent firestore query? The console logs the correct data, but my code only displays the last item in the loop inside ngFor. ...

Creating a fresh ngx-translate pipeline (comparing pure and impure methods)

Edit: I am looking to enhance the functionality of ngx-translate's pipe by extending it. Here is an example of how I achieved this: import { Pipe, PipeTransform } from '@angular/core'; import { TranslatePipe } from "@ngx-translate/core"; @ ...

Angular Material 2 Stepper Controls for Angular applications

I successfully implemented a linear stepper using the Angular Material 2 Stepper component. My project consists of forms in various components (component-a, component-b, component-c). I need the linear stepper in my main container component (container-com ...

Retrieving information from a Kendo grid cell

I am working on a web application that utilizes Kendo Grid. How can I retrieve the values of the "Ticket No" from the selected checkboxes? https://i.stack.imgur.com/aPOje.png This is my code: var grid = $("#poGrid").data("kendoGrid"); grid.items().filte ...

Having trouble mocking useAppSelector in Jest, RTL, Redux Toolkit, and React testing

I have react redux toolkit installed and have replaced vitest with jest for testing purposes. My goal is to test whether the modal window is rendered in the App component when the isOpen flag is true. I only mock the part of the store that is necessary, n ...

What is causing the Angular HTTP Post method error "Property 'post' is undefined"?

Encountering an error while using Angular's HTTP Post method: Cannot read property 'post' of undefined. I am attempting to send my first HTTP POST request, but it is not functioning as expected. export class RegisterComponent impleme ...

Struggling to implement the proper authentication method with API in Ionic

Having an API for the login, but being new to Ionic is causing difficulty in creating the correct method for the login process. The service file is located here: providers/restapi/restapi.ts import { HttpClient } from '@angular/common/http'; im ...

Adjusting the dimensions of the cropper for optimal image cropping

I am currently working on integrating an image cropper component into my project, using the react-cropper package. However, I am facing a challenge in defining a fixed width and height for the cropper box such as "width:200px; height:300px;" impo ...

What is the best way to incorporate a background image using ngStyle?

I need help populating multiple cards in the following way: <mdl-card *ngFor="let product of templates" class="demo-card-event" mdl-shadow="2" [ngStyle]="{ 'background-color': 'lightgray' }"> <mdl-card-title mdl-card-expan ...

My Angular2 application hosted on Heroku is experiencing issues with accessing configuration variables

I am currently developing a web page using Angular2 and I am interested in utilizing configuration variables from Heroku to keep certain sensitive information, such as API URLs, hidden from my script. I have already configured 2 variables on the settings p ...

Tips on how to flatten an Array of Observables within an Observable

I've been attempting to flatten a nested Observable, but I'm struggling to make it work as intended: this.af.object('test/father') .map(res => { res.namedKeys = []; for (let el in res.keys) { res.namedKeys.push(this ...

Is there a way to unselect a button in Angular?

I have a set of buttons representing different categories. When I click on a button, it displays a card with relevant information. <app-category-button [label]='category.name' [isSelected]='category.id === (selectedCategoryId$ | asy ...

What is the best way to determine if a local storage key is not present?

By applying the if condition below, I can determine whether or not the local storage key exists: this.data = localStorage.getItem('education'); if(this.data) { console.log("Exists"); } To check for its non-existence using an if conditi ...

Is it feasible to securely remove an item from an array within an object without the need for any assertions in a single function?

My interest in this matter stems from curiosity. The title may be a bit complex, so let's simplify it with an example: type ObjType = { items: Array<{ id: number }>; sth: number }; const obj: ObjType = { sth: 3, items: [{ id: 1 }, { id: 2 } ...

Observable doesn't respond to lazy loaded module subscriptions

I am trying to understand why my lazy loaded module, which loads the test component, does not allow the test component to subscribe to an observable injected by a test service. index.ts export { TestComponent } from './test.component'; export { ...