元素在视图中时的角度检查

ste*_*Kim 6 angular

在 angular 中,如何检测某个元素是否在视图中?

例如,我有以下内容:

<div class="test">Test</div>
Run Code Online (Sandbox Code Playgroud)

有没有办法检测这个 div 何时出现?

谢谢。

noa*_*myg 16

基于这个答案,适应角度:

模板:

<div #testDiv class="test">Test</div>
Run Code Online (Sandbox Code Playgroud)

成分:

  @ViewChild('testDiv', {static: false}) private testDiv: ElementRef<HTMLDivElement>;
  isTestDivScrolledIntoView: boolean;

  @HostListener('window:scroll', ['$event'])
  isScrolledIntoView(){
    if (this.testDiv){
      const rect = this.testDiv.nativeElement.getBoundingClientRect();
      const topShown = rect.top >= 0;
      const bottomShown = rect.bottom <= window.innerHeight;
      this.isTestDivScrolledIntoView = topShown && bottomShown;
    }
  }
Run Code Online (Sandbox Code Playgroud)

滚动事件绑定的示例

另一个不错的功能是确定其中有多少内容<div>被视为“在视图内”。这是对此类实现的参考。


Cre*_*rge 8

这是您可以使用的指令。它使用闪亮的IntersectionObserver API

该指令

import {AfterViewInit, Directive, TemplateRef, ViewContainerRef} from '@angular/core'

@Directive({
  selector: '[isVisible]',
})

/**
 * IS VISIBLE DIRECTIVE
 * --------------------
 * Mounts a component whenever it is visible to the user
 * Usage: <div *isVisible>I'm on screen!</div>
 */
export class IsVisible implements AfterViewInit {

  constructor(private vcRef: ViewContainerRef, private tplRef: TemplateRef<any>) {
  }

  ngAfterViewInit() {
    const observedElement = this.vcRef.element.nativeElement.parentElement

    const observer = new IntersectionObserver(([entry]) => {
      this.renderContents(entry.isIntersecting)
    })
    observer.observe(observedElement)
  }

  renderContents(isIntersecting: boolean) {

    this.vcRef.clear()

    if (isIntersecting) {
      this.vcRef.createEmbeddedView(this.tplRef)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

用法

<div *isVisible>I'm on screen!</div>
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

8962 次

最近记录:

4 年,3 月 前