0

I am showing a p-datatable inside a p-dialog in one of my component. If a user has previously selected few rows from this table, I need to show them selected when the user visits the p-dialog next time.

I am passing an array of selected items to the selection property of the p-datatable. However, the rows are not shown selected on the screen.

If I re-select the same rows, I get them twice in selection property, which means the pre-selected rows are rightly kept in selection property but somehow not binded to the html.

I have tried to wrap the entire p-dialog in an *ngIf expecting it to be created only after the data has been received but it made no difference.

What can I do to bind the selected rows to the p-datatable.

<div *ngIf="data && data.length" class="col-sm-12">
    <p-dataTable #ListRef [value]="data" rowHover="true" [multiSortMeta]="multiSortMeta" (onRowSelect)="onSelect($event)" [(selection)]="selectedData" (onRowUnselect)="onUnSelect($event)">
      <p-column  field="launchDate" header="Launch Date" [sortable]="true"></p-column>
      <p-column  field="endDate" header="End Date" [sortable]="true"></p-column>
    </p-dataTable>
  </div>

I have also tried fetching the reference using ViewChild and assigning the values to the selection property there. That too made no difference.

I however noticed that the issue does not come if I have the data and selectedData already available in my ngOnInit method.

Any ideas ?

Saurabh Tiwari
  • 4,632
  • 9
  • 42
  • 82
  • How are you passing an array of selected items to the selection property 'selectedData'? it is possible that view does not refresh after assignment. I suggest Try using spread operator instead of push. – TimeTraveler Sep 19 '17 at 05:24
  • I just assign the array to the `selection` property. – Saurabh Tiwari Sep 19 '17 at 05:32

1 Answers1

2

Though I missed it at first, I later found that there is a property dataKey which can be assigned for comparing the selected rows against total rows. This worked for me. The only change was to assign a field name to uniquely match the rows

<p-dataTable #fundListRef [value]="data" rowHover="true" [(selection)]="selectedData" (onRowSelect)="onFundSelect($event)" (onRowUnselect)="onFundUnSelect($event)"
         dataKey="id">

The p-datatable documentation says that it uses a map comparison which was somehow not working for my case.

Saurabh Tiwari
  • 4,632
  • 9
  • 42
  • 82