In angular, how do I detect if a certain element is in view?
For example, I have the following:
<div class="test">Test</div>
Is there a way to detect when this div is in view?
Thanks.
Based off this answer, adapted to Angular:
Template:
<div #testDiv class="test">Test</div>
Component:
@ViewChild('testDiv', {static: false}) private testDiv: ElementRef<HTMLDivElement>;
isTestDivScrolledIntoView: boolean;
@HostListener('window:scroll', ['$event'])
isScrolledIntoView(){
if (this.testDiv){
const rect = this.testDiv.nativeElement.getBoundingClientRect();
const topShown = rect.top >= 0;
const bottomShown = rect.bottom <= window.innerHeight;
this.isTestDivScrolledIntoView = topShown && bottomShown;
}
}
Example with scroll event binding
Another nice feature is to determine how much of that <div>
is to be considered as "within view". Here's a reference to such implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With