如何在角度2中使用自定义指令

时间:2020-07-02 06:10:42

标签: angular lazy-loading angular-directive custom-directive

我遵循了有关创建自定义指令的教程,以便像这样以延迟角度8加载图像:

import { AfterViewInit, Directive, ElementRef, HostBinding, Input } from '@angular/core';

@Directive({
  selector: 'img[appLazyLoad]'
})
export class LazyLoadDirective implements AfterViewInit {
  @HostBinding('attr.src') srcAttr = null;
  @Input() src: string;

  constructor(private el: ElementRef) {}

  ngAfterViewInit() {
    this.canLazyLoad() ? this.lazyLoadImage() : this.loadImage();
  }

  private canLazyLoad() {
    return window && 'IntersectionObserver' in window;
  }

  private lazyLoadImage() {
    const obs = new IntersectionObserver(entries => {
      entries.forEach(({ isIntersecting }) => {
        if (isIntersecting) {
          this.loadImage();
          obs.unobserve(this.el.nativeElement);
        }
      });
    });
    obs.observe(this.el.nativeElement);
  }

  private loadImage() {
    this.srcAttr = this.src;
  }
}

我有一个应呈现多个图像的组件(我正在考虑为“ src”创建一个数组),并且我想使用此指令,以使图像不会同时加载所有图像。在获得此代码的教程中,没有说明如何使用它。你能告诉我如何使用它吗?谢谢!

0 个答案:

没有答案
相关问题