From 3036b765db81670e20d514d6230b0f1d99ad47fd Mon Sep 17 00:00:00 2001 From: Ivan Kuplevich Date: Thu, 12 Nov 2020 17:24:34 +0300 Subject: [PATCH] fix: use selectedRowIndex if specified when data changes (#1221) --- projects/ng2-smart-table/src/lib/lib/grid.ts | 28 ++++++++++++++++++- .../src/lib/ng2-smart-table.component.ts | 7 ++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/projects/ng2-smart-table/src/lib/lib/grid.ts b/projects/ng2-smart-table/src/lib/lib/grid.ts index a53f0362b..f09aa05de 100644 --- a/projects/ng2-smart-table/src/lib/lib/grid.ts +++ b/projects/ng2-smart-table/src/lib/lib/grid.ts @@ -214,12 +214,22 @@ export class Grid { return false; } - // TODO: move to selectable? Separate directive + /** + * @breaking-change 1.8.0 + * Need to add `| null` in return type + * + * TODO: move to selectable? Separate directive + */ determineRowToSelect(changes: any): Row { if (['load', 'page', 'filter', 'sort', 'refresh'].indexOf(changes['action']) !== -1) { return this.dataSet.select(this.getRowIndexToSelect()); } + + if (this.shouldSkipSelection()) { + return null; + } + if (changes['action'] === 'remove') { if (changes['elements'].length === 0) { // we have to store which one to select as the data will be reloaded @@ -328,4 +338,20 @@ export class Grid { const maxPageAmount: number = Math.ceil(source.count() / perPage); return maxPageAmount ? Math.min(pageToSelect, maxPageAmount) : pageToSelect; } + + private shouldSkipSelection(): boolean { + /** + * For backward compatibility when using `selectedRowIndex` with non-number values - ignored. + * + * Therefore, in order to select a row after some changes, + * the `selectedRowIndex` value must be invalid or >= 0 (< 0 means that no row is selected). + * + * `Number(value)` returns `NaN` on all invalid cases, and comparisons with `NaN` always return `false`. + * + * !!! We should skip a row only in cases when `selectedRowIndex` < 0 + * because when < 0 all lines must be deselected + */ + const selectedRowIndex = Number(this.getSetting('selectedRowIndex')); + return selectedRowIndex < 0; + } } diff --git a/projects/ng2-smart-table/src/lib/ng2-smart-table.component.ts b/projects/ng2-smart-table/src/lib/ng2-smart-table.component.ts index 6bd17d4cc..b213821f9 100644 --- a/projects/ng2-smart-table/src/lib/ng2-smart-table.component.ts +++ b/projects/ng2-smart-table/src/lib/ng2-smart-table.component.ts @@ -42,7 +42,12 @@ export class Ng2SmartTableComponent implements OnChanges, OnDestroy { defaultSettings: Object = { mode: 'inline', // inline|external|click-to-edit selectMode: 'single', // single|multi - selectedRowIndex: 0, // points to an element in all data + /** + * Points to an element in all data + * + * when < 0 all lines must be deselected + */ + selectedRowIndex: 0, switchPageToSelectedRowPage: false, hideHeader: false, hideSubHeader: false,