元素在 View 中时的 Angular 检查

标签 angular

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

例如,我有以下内容:

<div class="test">Test</div>

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

谢谢。

最佳答案

基于此 answer ,适应 Angular:
模板:

<div #testDiv class="test">Test</div>
成分:
  @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;
    }
  }
Example with scroll event binding
另一个不错的功能是确定其中的多少 <div>被视为“在视野之内”。 Here's a reference到这样的实现。

关于元素在 View 中时的 Angular 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49215634/

相关文章:

angular - Angular 8 中的动态密码验证器

angular - DatePicker 在 Mat Dialog 窗口中不工作

javascript - NestJS 根据浏览器语言传递静态文件

angular - 获取当前页面并移动到 Primeng 数据表中的特定页面

angular - 使用 Angular Material 表从 Angular 2 中的表中删除选定的行

javascript - Angular 6 与 session 存储

javascript - 在 Angular 中使用 BehaviourSubject 在两个组件之间进行通信

Angular Material 2 - mat-paginator [length] 问题

angular - Ionic 2 和 ng-model

angular - Angular 7 的简单 ModalService 打不开 : No component factory found for