在 Angular 项目中,我想将 IntersectionObserver 的视口限制为 DOM 的特定部分。
我使用 id 定义要用作 root 的元素:
<div id="container">
<div class="page-list">
<infinite-scroll-page (scrolled)="onInfiniteScroll()">
...
</infinite-scroll-page>
</div>
</div>
在相应的组件中,我使用 getElementById 定义根:
export class InfiniteScrollPageComponent implements OnDestroy {
@Input() options: {root, threshold: number} = {root: document.getElementById('container'), threshold: 1};
@ViewChild(AnchorDirectivePage, {read: ElementRef, static: false}) anchor: ElementRef<HTMLElement>;
private observer: IntersectionObserver;
constructor(private host: ElementRef) { }
get element() {
return this.host.nativeElement;
}
ngAfterViewInit() {
const options = {
root: document.getElementById('container'),
...this.options
};
console.log("options: ", JSON.stringify(options));
//...
但是登录的root始终是null。
我做错了什么?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
首先,您的扩展运算符是错误的方式,因此不幸的是,您在使用
@Input()中的默认值设置后立即覆盖您的root赋值(据我所知,这不是实际上用作输入?)。解决这个问题可能只需要扭转这个局面:
const options = { root: document.getElementById('container'), ...this.options };应该是
const options = { ...this.options, root: document.getElementById('container') };其次,我想知道使用
@ViewChild并将对容器元素的引用从父级传递到InfiniteScrollPageComponent是否更有意义。parent.component.htmlparent.component.tsexport class ParentComponent { @ViewChild('Container') containerRef: ElementRef;
} infinite-page-component.component.tsexport class InfiniteScrollPageComponent { @Input() containerRef: ElementRef;
ngAfterViewInit() {
const options = {
...this.options
root: containerRef.nativeElement,
};
}