[英]How to implement IntersectionObserver on angular mat-table for lazy loading?
I want to lazy load more data as the user scrolls down the table and wanted to use IntersectionObserver.我想在用户向下滚动表格并想使用 IntersectionObserver 时延迟加载更多数据。 I am using bootstrap grid as the container.
我正在使用引导网格作为容器。 I used the code below but the callback is never triggered.
我使用了下面的代码,但从未触发回调。
This is my.html这是我的.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而在.ts文件中这个函数
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);
Add the id field to div.row element an observe the last row of the table将 id 字段添加到 div.row 元素并观察表格的最后一行
<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将项目添加到数据源后,再次重置观察者以观察表的最后一行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.