3 changed files with 44 additions and 3 deletions
@ -0,0 +1,38 @@ |
|||||
|
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(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue