How to get the selected row data item

3 Answers 2053 Views
General Discussions
Salim
Top achievements
Rank 1
Salim asked on 09 Aug 2018, 09:55 AM
hello, 

i'm trying to get the selected row data item, i was able to get the data item from the selected row using DOM
but when a grouping or filtering or sorting is applied the data is different, 
Is there a way to know the selected row data ?

Thank you  

3 Answers, 1 is accepted

Sort by
0
Dimiter Topalov
Telerik team
answered on 10 Aug 2018, 07:11 AM
Hello Salim,

There are couple of viable approaches to obtain the selected data item(s):

1) The selected item is available in the selectionChange event handler - e.selectedRows contains a collection of the selected rows and each such object has a dataItem property, e.g.:

public selectionChange(e) {
      this.selectedItem = e.selectedRows[0].dataItem;
    }

https://plnkr.co/edit/lAIB4jY1thbEQrJLQiBS?p=preview

2) You can keep a collection of all selected item and provide a function that returns the whole data item to the selectedKeys option, e.g.:

<kendo-grid
            [data]="gridView"
            [pageSize]="pageSize"
            [skip]="skip"
            [pageable]="true"
            (pageChange)="pageChange($event)"
            [height]="500"
            [kendoGridSelectBy]="selectedCallback"
            [selectedKeys]="mySelection"
            >

public mySelection: number[] = [];
...
public selectedCallback = (args) => args.dataItem;

https://plnkr.co/edit/wpnr9AR1ecnK3ntQxR1r?p=preview

I hope this helps.

Regards,
Dimiter Topalov
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Salim
Top achievements
Rank 1
commented on 10 Aug 2018, 08:55 AM

well actually I've seen the two proposed solution but what i need is to be able to reSelect from the code a certain row in the grid 

and this will not fire the selection change event and in my case i'm using the selectedCallback to return the index of the selected item to item to do this functionality 

do you have any other possible solution to do this ?

 

Thanks, 

Dimiter Topalov
Telerik team
commented on 13 Aug 2018, 12:25 PM

Hello Salim,

Indeed, when the selection is triggered programmatically, the selectionChange event will not fire, but the second approach from my previous response (the one relying on the callback and keeping the collection of selected items) can be easily adjusted to better match the scenario:

https://plnkr.co/edit/SIrf1KONO5QIQ0BAUN7q?p=preview // keep selection collection by whole data items

https://plnkr.co/edit/OR4tuxV98sor18Aw4dI3?p=preview // keep a collection of the IDs of the selected items and use custom logic to retrieve the whole data items by ID

You can keep a collection of the IDs of the selected items (or the whole items - in accordance with your preference). You can select new items programmatically (or change the selection in any other way) by simply manipulating the array "mySelection".

This way you will have access to all currently selected IDs (or whole items) at any given moment.

Regards,
Dimiter Topalov
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Salim
Top achievements
Rank 1
commented on 27 Aug 2018, 12:56 PM

i was able to do what i want using  your proposed solution (https://plnkr.co/edit/SIrf1KONO5QIQ0BAUN7q?p=preview // keep selection collection by whole data items)
but what i need now is to be able to focus the grid cell based on my selection
i'm using the below: 
 var kendoRowIndex = selectedRowIndex + 1;// header row
    if (this.filterable === true) {
      kendoRowIndex++;
    }
    this.grid.focusCell(kendoRowIndex, 0);

i need to get the selected row index with all the filter/grouping/pagination applied 
how can i do this?
Salim
Top achievements
Rank 1
commented on 27 Aug 2018, 01:20 PM

And one more thing is how to be able to select the first row of the grid with all the filter/grouping/pagination applied

Thank you in advanced 

Dimiter Topalov
Telerik team
commented on 28 Aug 2018, 11:11 AM

Hi Salim,

You can select the first item of the current page after the data is processed in accordance with the current Grid state by updating the mySelection collection accordingly, e.g.:

private loadItems(): void {
        this.gridView = {
            data: this.items.slice(this.skip, this.skip + this.pageSize),
            total: this.items.length
        };
         
        this.mySelection = [this.gridView.data[0]];
    }

https://plnkr.co/edit/xNjJ41WsFG5qD6QAyBDt?p=preview

Depending on the desired behavior, you can either add the item to a previously existing collection, or set the whole collection of selected items to only one item - the first one for the given page.

I hope this helps.

Regards,
Dimiter Topalov
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Salim
Top achievements
Rank 1
commented on 28 Aug 2018, 01:16 PM

Hi Dimiter,

that works only for pagination, what about when i'm having grouping do i need to re process the data ?

Thank you 

Dimiter Topalov
Telerik team
commented on 30 Aug 2018, 08:40 AM

Hello Salim,

Indeed, the example demonstrates how to select the first row on the new page after paging only, as it is based on the example, linked in the question. To handle all Grid data operations like paging, sorting, filtering and grouping, we need to handle the dataStateChange event (as opposed to the pageChange event) and update the Grid data in accordance with the current State (paging, sorting, filtering and grouping info):

https://www.telerik.com/kendo-angular-ui/components/grid/data-binding/automatic-operations/

Here is the updated example that handles all data operations (utilizing the Data Query process() function), and performs the logic, related to selecting the first item in the newly rendered set of data after data is processed in accordance with the new State:

https://plnkr.co/edit/ktXwFesSWeB0iXVNrpod?p=preview

The only difference worth noting in the context of grouping, is that the data property of the GridDataResult object, created by processing the data, is now an array of group objects and the items, associated with each group, are in this object's "items" property, so the first for the displayed data set would be:

this.mySelection = [this.gridView.data[0].items[0]]

Regards,
Dimiter Topalov
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Bob
Top achievements
Rank 1
Veteran
commented on 30 Aug 2018, 09:26 AM

HI Dimiter,

A lot of useful information in there.  Thanks.

Bob

Salim
Top achievements
Rank 1
commented on 30 Aug 2018, 09:54 AM

Hello Dimiter, 

That works actually when i have one grouping but when the user adds 2 grouping or more the GridDataResult object is again  an array of group objects and the items, associated with each group

Note that i was able to arrive to same result using (this.grid.view.first.items)

Is There any suggested solution to this case ?

Thank you in advanced 

Dimiter Topalov
Telerik team
commented on 31 Aug 2018, 12:51 PM

Hello Salim,

Indeed the demonstrated approach will work for data, grouped by one field only. However the same approach can be used for multiple levels of grouping by introducing a custom method that will return the first data item from the first innermost group after inspecting the data collection recursively, e.g.:

private loadItems(): void {
        this.gridView = process(products, this.state)
         
        if(this.state.group && this.state.group.length) {
          console.log(this.gridView);
          this.mySelection = [this.extractFirstDataItem(this.gridView.data)];
        } else {
          this.mySelection = [this.gridView.data[0]];
        }
    }
     
    private extractFirstDataItem(groupedData) {
      if(groupedData[0].items) {
        return this.extractFirstDataItem(groupedData[0].items);
      } else {
        return groupedData[0];
      }
    }

https://plnkr.co/edit/m0ZKfXg1C46c1vnVuYWQ?p=preview

I hope this helps.

Regards,
Dimiter Topalov
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
congdongdientu.
Top achievements
Rank 1
Veteran
commented on 25 May 2020, 07:10 AM

Hi guy
How could i change the select state with single and multi check in ngFor. Hope you help me, thanks a lot :)

<kendo-grid
[selectable]="true"
kendoGridSelectBy="stockId"
[selectedKeys]="selectedKeys"
(selectedKeysChange)="onSelectedKeysChange($event)">
<ng-template kendoGridHeaderTemplate let-column let-columnIndex="columnIndex" *ngIf="colItem.fieldName === 'isShowCheckbox'">
                <input class="k-checkbox" id="selectAllCheckboxId" kendoGridSelectAllCheckbox
                    [state]="selectAllState"
                    (selectAllChange)="onSelectAllChange($event)">
                <label class="k-checkbox-label" for="selectAllCheckboxId"></label>
            </ng-template>
 <kendo-grid-column
              *ngFor="let colItem of viewOptions.userGridColumnSettings"
              [field]="colItem.fieldName"
              [title]="colItem.fieldTitle"
              [width]="colItem.width"
              [hidden]="colItem.isHidden"
              [format]="colItem.format"
              [filter]="colItem.filter"
              >
</kendo-grid-column>
</kendo-grid>

Ivan
Telerik team
commented on 27 May 2020, 06:24 AM

Hi Salim,

If I understood correct the request , you can control checked state by using selectedKeys in combination of kendo-grid-checkbox-column, like in this stackblitz sample.

Please do not hesitate further question if any appear.

Regards,
Ivan
Progress Telerik

Progress is here for your business, like always. Read more about the measures we are taking to ensure business continuity and help fight the COVID-19 pandemic.
Our thoughts here at Progress are with those affected by the outbreak.
JoeThomas
Top achievements
Rank 1
Veteran
commented on 20 Jul 2020, 06:21 AM

Hi, I posted a question here, 

https://stackoverflow.com/questions/62975650/angular-kendo-grid-select-row-programatically

 

I am trying to Select an Angular Kendo Grid Rows Programatically, using
1 )
this.selectedProductIds = [1,5,8]<kendo-grid [selectedKeys] = "selectedProductIds"[kendoGridSelectBy] = "'productId'"
https://www.telerik.com/kendo-angular-ui/components/grid/api/SelectionDirective/

2 ) However, another coworker before already in the code, is doing this to find the persisted rows.

public selectedCallback = (args) => args.dataItem;<kendo-grid [data]="gridView"[pageSize]="pageSize"[kendoGridSelectBy]="selectedCallback"[selectedKeys]="mySelection">

It doesn't make sense, its like Telerik setup two uses/arguments for kendoGridSelectBy, one with a string, one a function. Now, I'm not sure how to programatically Select data. Does anyone have a solution? Anyway help would be great.

https://www.telerik.com/forums/how-to-get-the-selected-row-data-item

 

Dimiter Topalov
Telerik team
commented on 21 Jul 2020, 09:16 AM

Hi Joe,

Both approaches are valid - kendoGridSelectBy input can be bound to a string, representing the unique property/key each data item has (like ID), or to a callback, returning a string or the whole item.

In both cases, the returned value will be the one the items will be compared by when determining whether the respective Grid row should be selected or not. When the directive input is bound directly to a string, items will be compared using the value, corresponding to the provided string property name each data item has. When the whole data item is returned from the provided callback, the data item objects will be compared.

The selectedKeys collection will be populated with either the values, corresponding to the provided property name (when a string is used), or with the data item objects themselves (when a callback is used and the  whole data item object is returned). For example, if the data items have unique productId property, the selectedKeys array will contain the IDs of the selected items, e.g. [1, 3, 5]. When the callback is used, and the data item is returned, the selectedKeys array will contain the data item objects. Each item of the selectedKeys array will be compared to the data items in the Grid data, and matching items will be selected - when the array contains for example numbers (IDs), the Grid selection will contain the data items whose IDs match the items in the array. When the array contains objects, they will be compared against the Grid data objects and the ones that are the same object instance will be selected.

I hope this makes things clearer, but let us know if you have further questions.

Regards,
Dimiter Topalov
Progress Telerik

0
Bob
Top achievements
Rank 1
Veteran
answered on 15 Aug 2018, 05:03 PM

Hi Sam,

The answer in finding the selected row in a grid where the state (filtering, sorting, grouping etc) has been set is to persist the state first.  My use case is to use the grid as a navigation item, users drill down to entities from individual rows and then have an option to return to the grid from the details page.  By setting the current state on the button used for the drill down and reloading it when the user returns to the grid page you can then select the correct page of the grid with sorting, grouping and filtering applied and highlight the appropriate row as selected.  Is this what you are trying to do?  If you are then I am only too happy to share some code.

Cheers,

Bob

Salim
Top achievements
Rank 1
commented on 24 Aug 2018, 01:49 PM

what i'm actually trying to do is to add a double click event to the grid and i want to pass the data Item related to this row

 

Salim
Top achievements
Rank 1
commented on 27 Aug 2018, 07:55 AM

i was able to do what i want using  your proposed solution (https://plnkr.co/edit/SIrf1KONO5QIQ0BAUN7q?p=preview // keep selection collection by whole data items)

but what i need now is to be able to focus the grid cell based on my selection

i'm using the below: 

 var kendoRowIndex = selectedRowIndex + 1;// header row
    if (this.filterable === true) {
      kendoRowIndex++;
    }
    this.grid.focusCell(kendoRowIndex, 0);

 

i need to get the selected row index with all the filter/grouping/pagination applied 

how can i do this?

0
Bob
Top achievements
Rank 1
Veteran
answered on 27 Aug 2018, 08:28 AM

Hi Salim,

In your grid when you make the select event, pass the id.  My code is much more complex but the below should help you;

ngOnInit() {
if (this.from === 'from-entity-read') {
//get grid config setting from localstorage, find the entity in the grid.
const storedGridSettings = localStorage.getItem('ncEntityGridSettings');
if (storedGridSettings) {
let settings = JSON.parse(storedGridSettings);
this.gridSettings.state = settings.state;
if (settings.state.filter) {
this.mapDateFilter(settings.state.filter);
}
if (settings.columnsConfig) {
//how to get an instance of the grid and then loop the columns and apply settings from the gridSettings.columnsConfig object
//this.gridSettings.columnsConfig = settings.columnsConfig.sort((a, b) => a.orderIndex - b.orderIndex);
}
this.hasSettings = true;
if (settings.id) {
this.selectedIds.push(settings.id);
}
}
}
this.getEntitiesForKendo();
}

In the example above I am checking to see where the user came from and, if appropriate, loading values from local storage.  Your key here is the line where we are pushing the selected id to the selectedIds array which is used for the [selectedKeys] property of the grid.

I know this is not exactly what you wanted but I hope it helps you along the way.

 

Salim
Top achievements
Rank 1
commented on 27 Aug 2018, 12:56 PM

i was able to do what i want using  your proposed solution (https://plnkr.co/edit/SIrf1KONO5QIQ0BAUN7q?p=preview // keep selection collection by whole data items)
but what i need now is to be able to focus the grid cell based on my selection
i'm using the below: 
 var kendoRowIndex = selectedRowIndex + 1;// header row
    if (this.filterable === true) {
      kendoRowIndex++;
    }
    this.grid.focusCell(kendoRowIndex, 0);

i need to get the selected row index with all the filter/grouping/pagination applied 
how can i do this?
Tags
General Discussions
Asked by
Salim
Top achievements
Rank 1
Answers by
Dimiter Topalov
Telerik team
Bob
Top achievements
Rank 1
Veteran
Share this question
or