搜尋

首頁  >  問答  >  主體

使用 getElementById 的 IntersectionObserver 的根始終為 null

在 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

我做錯了什麼?

P粉501683874P粉501683874319 天前466

全部回覆(1)我來回復

  • P粉071602406

    P粉0716024062024-03-29 16:31:45

    首先,您的擴充運算子是錯誤的方式,因此不幸的是,您在使用@Input() 中的預設值設定後立即覆寫您的root賦值(據我所知,這不是實際上用作輸入?)。

    解決這個問題可能只需要扭轉這個局面:

    const options = {
      root: document.getElementById('container'),
      ...this.options
    };

    應該是

    const options = {
      ...this.options,
      root: document.getElementById('container')
    };

    其次,我想知道使用 @ViewChild 並將容器元素的引用從父級傳遞到 InfiniteScrollPageComponent 是否更有意義。

    parent.component.html

    ...

    parent.component.ts

    export class ParentComponent {
      @ViewChild('Container') containerRef: ElementRef;
    }

    infinite-page-component.component.ts

    export class InfiniteScrollPageComponent {
      @Input() containerRef: ElementRef;
    
      ngAfterViewInit() {
        const options = {
          ...this.options
          root: containerRef.nativeElement,
        };
      }

    回覆
    0
  • 取消回覆