要检测Angular 7中的组件是否在可视区域内,可以使用Intersection Observer API。以下是一个示例代码:
npm install intersection-observer
import 'intersection-observer';
import { Component, OnInit, ElementRef } from '@angular/core';
@Component({
  selector: 'app-my-component',
  template: '',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
  constructor(private elementRef: ElementRef) { }
  ngOnInit() {
    const options = {
      root: null, // 可视区域的根元素,默认为浏览器视口
      rootMargin: '0px', // 根元素的边距
      threshold: 1.0 // 当目标元素可见度达到指定阈值时触发回调函数
    };
    const observer = new IntersectionObserver(this.handleIntersection, options);
    observer.observe(this.elementRef.nativeElement);
  }
  handleIntersection(entries, observer) {
    entries.forEach(entry => {
      if (entry.intersectionRatio > 0) {
        console.log('组件可见');
      } else {
        console.log('组件不可见');
      }
    });
  }
}
在上面的代码中,我们创建了一个Intersection Observer实例,并在组件的ngOnInit方法中调用了observer的observe方法来观察当前组件元素。当组件元素的可见度达到指定的阈值时,handleIntersection回调函数将被触发。根据intersectionRatio属性的值,我们可以判断组件是否在可视区域内。
请注意,上述代码中使用了ElementRef来获取组件元素的引用。确保在组件的构造函数中注入了ElementRef,并将其传递给Intersection Observer实例。