0

I am trying to get reference of the first row to allow arrow key navigation on table rows. I tried with the below code with the function, that is working in development build, but in production build angular removes ng-reflect bindings so I am not able to get reference. Is there any solution?

   getElementByXpath(path) {
   return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
 }
   let firstRow: any = this.getElementByXpath('//datatable-body-row[@ng-reflect-row-index="0"]');
   if(firstRow) {
     firstRow.focus();
   }

2 Answers2

1

In your template add template reference variable (in my case it is #table). If you check documentation you will find there is an input to datatable called selected and selectionType. Documentation

Your template should look like this:

    <ngx-datatable
    #table
    class="bootstrap"
    [headerHeight]="50"
    [limit]="5"
    [columnMode]="ColumnMode.force"
    [footerHeight]="50"
    rowHeight="auto"
    [rows]="rows"
    [selected]="selected"
    [selectionType]="SelectionType.single">

In your component add property selected;

export class AppComponent {
  selected = [];

Now in constructor you can easily focus on first row by using this.selected = [data[0]];. Maybe a better place to focus on first row is in one of Angular lifecycle hooks

Here is Stackblitz demo: https://stackblitz.com/edit/angular-ivy-nsmcki?file=src/app/app.component.ts

Demo is modification of code sample given here: https://swimlane.github.io/ngx-datatable/#single-selection

0

I solved this issue by using document.getElementByClassName. But this solution only will work for the first table that exist in dom.

const element: any = document.getElementsByClassName("datatable-body-row").item(0);
if (element) {
   element.focus();
}
  • Just wondering if you have found or went with an alternative solution to this. I'm dealing with a similar case. – edjm Mar 17 '20 at 19:51