You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

38 lines
1.1 KiB

import { Directive, ElementRef, EventEmitter, Output, AfterViewInit, OnDestroy, NgZone } from '@angular/core';
@Directive({
selector: '[appLazyLoad]',
standalone: true
})
export class LazyLoadDirective implements AfterViewInit, OnDestroy {
@Output() lazyLoad = new EventEmitter<void>();
private observer!: IntersectionObserver;
constructor(private element: ElementRef, private ngZone: NgZone) {}
ngAfterViewInit(): void {
// Run the intersection observer outside Angular's zone
this.ngZone.runOutsideAngular(() => {
this.observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Re-enter Angular's zone to trigger the lazy load event
this.ngZone.run(() => {
this.lazyLoad.emit();
this.observer.disconnect(); // Disconnect after loading
});
}
});
});
this.observer.observe(this.element.nativeElement);
});
}
ngOnDestroy(): void {
if (this.observer) {
this.observer.disconnect();
}
}
}