Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to table row or list item in an Angular app

In the code snapshot below in app.component.html, I display clickable rows in a table in Lines 39 to 58. Once the user clicks a row, I display other relevant rows in a table named suraTable as shown in Lines 63 to 77. Namely, when the user clicks on a row, the function onSelectAya(aya, suraTable) in app.component.ts is called. That function loads the necessary rows and the table is displayed.

What I am stuck with is this. Suppose suraTable ends up with 100 rows. The current behaviour is that rows 1, 2, 3... are displayed of course. I need to be able to show the table at Row 50 say (information carried in the parameter aya on Line 91). How do I scroll to that position? I tried the scrollTop way but when checking the values before and after the setting of suraTable.scrollTop, the value is always 0 (0 pixels that is). Line 100 shows that when console.log(suraTable) is reached, expected output is generated in the browser, which means that I am getting hold of the element correctly to start with.

So, how do I scroll to a specific row in a table, or to an item in a list (I could convert the whole structure to a list if easier) from within the app.component.ts component? Thank you.

enter image description here

like image 984
mohsenmadi Avatar asked Oct 14 '25 03:10

mohsenmadi


2 Answers

<mat-row id="{{task.taskId}}"
                *matRowDef='let task; columns: columnsReadyTask;let i = index;'></mat-row>

if working with datasources, you will need some delay after getting element on the page with id...

setTimeout(() => {
      const selectedRow = document.getElementById(taskId);
      if(selectedRow) {
        selectedRow.scrollIntoView({block: 'center'});
      }
    }, 500);
like image 100
Sanid Sa Avatar answered Oct 16 '25 20:10

Sanid Sa


This may not work on old browsers.

If this is simply a scrolling thing, you could add specific id to your rows so you can know theyr number, and then do

var elmnt = document.getElementById("rowNumber"+rowNumber);
elmnt.scrollIntoView();

If when the scrolling is taking part your element is not rendered on DOM, try adding a callback for when that rendering is finished. If that is not possible, maybe a setTimeout can do.

like image 42
Gabriel Slomka Avatar answered Oct 16 '25 20:10

Gabriel Slomka