Home:ALL Converter>Persist PrimeNG DataTable selection on route change

Persist PrimeNG DataTable selection on route change

Ask Time:2016-08-22T21:57:23         Author:DGarvanski

Json Formatter

I'm using a PrimeNG data table in an Angular 2 application and I have to persist the selection on route change. Currently, I'm setting the app state like so:

onTableRowStateChange() {
  this.appState.set('selectedApplicants', this.selectedApplicants);
}

Where appState is a service that saves the selection state. This is also used to persist some tabs which open up on selection.

While the appState is correctly set, returns an array of selected applicants and persists opened tabs, it does not persist the actual selection in the data table thus entries can be selected again.

The HTML looks like this:

<p-dataTable tableStyleClass="table" [value]="applicants"
                 [(selection)]="selectedApplicants"
                 (onRowSelect)="onTableRowStateChange()"
                 (onRowUnselect)="onTableRowStateChange();">
      <header>Applications</header>
      <p-column [style]="{'width':'38px'}" selectionMode="multiple"></p-column>
      <p-column *ngFor="let col of cols" [field]="col.field" [header]="col.header"></p-column>
</p-dataTable>

I tried using a this.appState.get('selectedApplicants') method to get the selectedApplicants array during `ngOnInit, in the constructor and even setting it like so:

selectedApplicants:any[] = ( this.appState.get('selectedApplicants').length > 0 ) ? this.appState.get('selectedApplicants') : this.appState.set('selectedApplicants', []);

in the component.

However, while it does return an array of selected applicants it doesn't select them in the table itself.

As a side note, doing this.selectedApplicants.splice(event.index, 1); on closing the tab deselects the table entry, so it is possible to programatically change selection by altering the selected entries array. It just doesn't select the entries automatically on initiating the view after a route change even if the required array is present.

Is there a workaround or any way to persist the data table selection on route change?

Author:DGarvanski,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/39081482/persist-primeng-datatable-selection-on-route-change
yy