在 Angular 中滚动到顶部时获取每个元素的 ID

Get id of each element when scroll to top in Angular

我想在部分元素到达顶部时获取该部分元素的 ID。 也做了类似的事情,但我希望 Angular 也一样。我以类似的方式尝试但没有成功。

/*let content = document.getElementsByClassName('scrollable');
      this.listener = this.renderer2.listen('window', 'scroll', (e) => {
        
        let elementPos = el.getBoundingClientRect().top + window.pageYOffset;
    
        
        var el = Array.prototype.forEach.call(content, (el)=>{
            // console.log(el.id, el.getBoundingClientRect().bottom, parseInt(el.clientHeight))
            if(el.getBoundingClientRect().bottom >= parseInt(el.clientHeight)) {
              console.log({el})
            }
        })
        
        */
section {background: #ccc; height: 100vh;};
section:nth-child(odd) {background: red}
<section class="scrollable" id="scroll1"> Scroll1 </section>
<section class="scrollable" id="scroll2"> Scroll2 </section>
<section class="scrollable" id="scroll3"> Scroll3 </section>
<section class="scrollable" id="scroll4"> Scroll4 </section>
<section class="scrollable" id="scroll5"> Scroll5 </section>

我可以通过一些实验让它自己工作。下面的代码可能会有所帮助。谢谢

      let content = document.getElementsByClassName('scrollable');
      // let windowTop = window.scroll.offset()
      this.listener = this.renderer2.listen('window', 'scroll', (e) => {
        
        
          let scrollY = this.windowRef.nativeWindow.pageYOffset;
           let landingPage = Array.prototype.filter.call(content, (el)=>{
            //  console.log(el.id, scrollY, el.getBoundingClientRect().top)
              return scrollY > (el.getBoundingClientRect().top + window.pageYOffset - 80);
            })

            // console.log({landingPage})
            console.log(landingPage.at(-1).id)           
      
        });

.....已编辑.....

我尝试更正@Mahdi Zarei 代码并得到了一些结果。 stackblitz demo

import { AfterViewInit, Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
  constructor() {}

  ngAfterViewInit() {
    // @ts-ignore
    const sections : any = Array.from(
      document.getElementsByClassName('scrollable') as HTMLCollectionOf<HTMLElement>
    ).map((section) => [section.id, section.offsetTop]);
    window.addEventListener('scroll', function (ev) {
      let foundIndex = 0;
      sections.forEach((sec, index) => {
        if (document.scrollingElement.scrollTop >= sec[1]) {
          foundIndex = index;
        }
      });
      document.getElementById('el').innerText = sections[foundIndex][0];
    });
  }
}


我做了这个stackblitz

我存储了 offsetTop 个部分并在 window 上添加了一个用于滚动的侦听器并检查它是否达到了阈值。