ilovejavaAJ
ilovejavaAJ

Reputation: 1841

How to get the date of [(selection)] of primeNg data table. Angular 2

I have an angular 2 project which uses primeng table wih multiple selection function. The selected value are stored in the [(selection)]. My question is how can I call/use the [(selection)] value in the component.ts. I tried logging the [(selection)] value in the console but getting an error.

<p-dataTable [value]="persons" selectionMode="multiple" [(selection)]="selectedPersons" dataKey="personId">
    <p-header>Excluded Stores</p-header>
    <p-column field="personId" header="person Id" [sortable]="true"></p-column>
    <p-column field="personFirstName" header="First Name" [sortable]="true"></p-column>
    <p-column field="personLastName" header="Last Name" [sortable]="true"></p-column>                   
</p-dataTable>
<button (click)="showPersonsSelected()"> Show List of person selected </button>

in my Component

export class SelectclusterComponent{

persons = [];

selectedPersons: person [];

showPersonsSelected(){
 console.log(this.selectedPersons);
}

}

Upvotes: 1

Views: 5401

Answers (4)

Sherif Fahd
Sherif Fahd

Reputation: 131

there is an Event Emitter "selectionChange" the event equal selections value

   <p-table
    #dt
    [value]="users"
    [(selection)]="selectedUser"
    dataKey="id"
    selectionMode="multiple"
    [selectionPageOnly]="true"
    (selectionChange)="onSelect($event)"
  >
  </p-table>

in ts file

 onSelect(selectedUsers: User[]) {
  console.log(selectedUsers);
 }

Upvotes: 0

Chi.che
Chi.che

Reputation: 33

Please add function onRowSelect into tag p-dataTable below:

<p-dataTable [value]="persons" selectionMode="multiple" [(selection)]="selectedPersons" dataKey="personId" (onRowSelect)="onRowSelect($event)">

In .component.ts get information of selected row below:

onRowSelect(event) {
    console.log(`Query selected: ${event.data.orderNumber} - ${event.data.country}`);
  }

Upvotes: 1

You also can use ViewChild to access Datatable class directly in component:

Template:

<p-dataTable #tbUsers ...></p-dataTable>

Component

import { ViewChild } from '@angular/core';
import { DataTable } from 'primeng/primeng';

@ViewChild('tbUsers') tbUsers: DataTable;

rowSelected(){
    console.log(this.tbUsers.selection);
}

Upvotes: 1

Aravind
Aravind

Reputation: 41571

You should be using onRowSelected event as below,

<p-dataTable (onRowSelect)="rowSelected($event)" selectionMode="multiple"
          [value]="tableData" [(selection)]="selectedData" 
           dataKey="model" [responsive]="true">
    <p-column field="orderNumber" header="Order Number"></p-column>
    <p-column field="country" header="Country"></p-column>
</p-dataTable>

And you have the selected items

 rowSelected(event){
    console.log(this.selectedData);
  }

LIVE DEMO

Upvotes: 0

Related Questions