#How to access ViewChid.nativeElement childrens - DOM reference?

3 messages · Page 1 of 1 (latest)

queen lotus
#

While trying to implement infinite scroll using IntersectionObserver i encounter such issue.
Im having a parent component (named ScrollComponent) that allows content projection.
Inside that ScrollComponent i may have multiple elements projected into its template.
Now i want somehow map through all of Scroll Component children and observe on them with IntersectonObserver.
Problem is i dont know how to acces their.. referenece in DOM something like using .target method i guess?

APP COMPONENT: 
  <app-infinite-scroll>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
    <div>10</div>
  </app-infinite-scroll>

APP INFINITE SCROLL COMPONENT: 
<div #observerRef class="scroll-container">
  <ng-content></ng-content>
</div>
  ngAfterContentInit (): void {
    this.observer = new IntersectionObserver(this.intersection, {
      threshold: 1
    });
    this.observer.observe(this.observerRef?.nativeElement.children);
  }

  private intersection(entries: IntersectionObserverEntry[]): void {
    entries.forEach((entry: IntersectionObserverEntry) => {
      if (entry.isIntersecting) {
        this.observer.unobserve(entry.target);
        this.lastOptionObserved?.emit();
      }
    });
  }

i was trying multiple things to acces nativeElement childrens but they are not referencing to their DOM elements, i tried:

    this.observer.observe(this.observerRef?.nativeElement.children);

    this.observer.observe(this.observerRef?.nativeElement.childNodes);

Does any one have an idea how i can access them ?

There is link to the demo of the problem recreated on stackBlitz
https://angular-ydjk1h.stackblitz.io

Thanks for help guys 🙂

uncut cedar
#

hello have you try to move the code in afterviewInit lifecycle ?

#

I have reproduced your problem, as you can see on the image the ngAfterContentInit method is triggered before the ngAfterViewInit