Desired outcome: call method sendNotification()
when a component first gets into view as the user scrolls down.
My solution (code follows):
- Listen for window:scroll as learned reading this question
- Doing some calculations to check if the element is in view
- Calling the method
export class GalleryComponent implements OnInit {
hintSent: boolean = false
constructor(private _elementRef: ElementRef, private _notificationService: NotificationsService) { }
ngOnInit(): void {
}
@HostListener("window:scroll", [])
onWindowScroll() {
let elem: Element = this._elementRef.nativeElement
let top = elem.getBoundingClientRect().top
let height = elem.getBoundingClientRect().height
let noti = new Notification('Tocca le immagini','Scopri altri dettagli sul nostro prodotto interagendo con le immagini')
if(top - window.innerHeight < 0 && top height - window.innerHeight > 0)
//this component is in view
if(this.hintSent == false)
this._notificationService.sendNotification(noti)
this.hintSent = true
}
}
The problem with my solution:
While angular renders the page the layout shift triggers the scroll event and calls the desired method before time since the user has not scrolled down yet. Now I could start listening for the scroll after a timeout or after the document.loaded event but is there a better solution?
CodePudding user response:
You should add your listener once you know your element has been created in view, hence in the lifecycle hook ngAfterViewInit
. Your nativeelement may be wrong or not even exist before that.