2

I want to lazy load more data as the user scrolls down the table and wanted to use IntersectionObserver. I am using bootstrap grid as the container. I used the code below but the callback is never triggered.

This is my .html

<div class="container">
<div class="row" style="max-height: 80vh; overflow: auto">
<table
  id="scrollArea"
  mat-table
  [dataSource]="dataSource"
  matSort
>
  <!-- ID Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>ID</th>
    <td mat-cell *matCellDef="let row">
      {{ row.id }}
    </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
    <td mat-cell *matCellDef="let row">
      {{ row.name }}
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>

  <!-- Row shown when there is no matching data. -->
  <tr class="mat-row" *matNoDataRow>
    <td class="mat-cell" colspan="4">
      No data matching the filter "{{ input.value }}"
    </td>
  </tr>
</table>
</div>
</div>

And in the .ts file this function

observe() {
 let options = {
   root: document.querySelector('#scrollArea'),
   rootMargin: '0px',
   threshold: 0.1,
 };

 const observer = new IntersectionObserver((entries) => {
   entries.forEach((entry) => {
     if (entry.isIntersecting) {
       console.log('observed');
      // run your code here
      // observer.disconnect(); // disconnect if you want to stop observing else it will rerun every time its back in view. Just make sure you disconnect in ngOnDestroy instead
    }
    console.log('observing outside');
  });
}, options);
Tea Zulo
  • 65
  • 1
  • 6
  • 14

1 Answers1

0

Add the id field to div.row element an observe the last row of the table

<div id="scrollArea" class="row" style="max-height: 80vh; overflow: auto">
<table

  mat-table
  [dataSource]="dataSource"
  matSort
>
...
</table>
</div>
observe() {
  let options = {
    root: document.querySelector('#scrollArea'),
    rootMargin: '0px',
    threshold: 0.1,
  };

  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      console.log(entry)
      if (entry.isIntersecting) {
        console.log('observed');
        // run your code here
        // observer.disconnect(); // disconnect if you want to stop observing else it will rerun every time its back in view. Just make sure you disconnect in ngOnDestroy instead
      }
      console.log('observing outside');
    });
  }, options);

  observer.observe(this.mytable.nativeElement.querySelectorAll('.mat-row')[this.dataSource.length-1] as HTMLElement);
}

after adding items to the datasource, reset the observer again to observe the last row of the table

Mr. Stash
  • 2,940
  • 3
  • 10
  • 24