I have an issue with a directive that I created in Angular. In this directive, I want to execute some code after the window.onload event to be sure that all the page resources have been loaded (because I want to know the page top offset of some elements in the directive and if the images are not loaded, this offset is not correct)
If I refresh the page, it works because of the window.onload event is fired but when using the angular navigation to reach my component, this event is not fired anymore. I tried to use the lifecycle of angular like AfterViewInit but most of the time the AfterViewInit method is executed before the images are loaded.
UPDATE This is the code of my directive :
export class ParallaxDirective implements OnInit, OnDestroy {
@Input() coef = 1;
start = 0;
path = 0;
initialTranslate = 0;
intersectObserver: IntersectionObserver;
inView: boolean;
constructor(
private element: ElementRef
) {
}
ngOnInit(): void {
window.addEventListener('load', () => this.initParallax());
}
ngOnDestroy(): void {
this.intersectObserver.unobserve(this.element.nativeElement);
window.removeEventListener('scroll', () =>this.setTransform());
}
initParallax(): void {
this.intersectObserver = new IntersectionObserver(this.intersect.bind(this));
this.intersectObserver.observe(this.element.nativeElement);
const initialY = new DOMMatrixReadOnly(window.getComputedStyle(this.element.nativeElement).getPropertyValue('transform')).m42;
this.start = this.element.nativeElement.offsetTop + initialY;
this.path = this.element.nativeElement.clientHeight;
this.initialTranslate = (initialY /
this.element.nativeElement.clientHeight) * 100;
if (window.pageYOffset > 0) {
this.setTransform(true);
}
window.addEventListener('scroll', () => this.setTransform());
}
setTransform(force = false): void {
if (!this.inView && !force) {
return;
}
const offset = window.pageYOffset + window.innerHeight - this.start;
const t = (offset * 10) / this.path;
const i = t * this.coef + this.initialTranslate;
this.element.nativeElement.style.setProperty('transform', `translate3d(0, ${i}%, 0)`);
}
intersect(entries: IntersectionObserverEntry[], observer: IntersectionObserver): void {
entries.forEach(entry => {
this.inView = entry.isIntersecting || entry.intersectionRatio > 0;
});
}
}
As you can see, I need to retrieve some offsets and dom elements height. The problem is that these offsets and heights are not the same after resources in the page (like images) are completely loaded that's why I need to have an event like window.onload to be sure that everything is loaded. And I didn't find any Angular lifecycle that should be triggered after resources load.
I hope someone can help me with this.
Thanks.