Home > Mobile >  Easy Angular way to detect if element is in viewport on scroll
Easy Angular way to detect if element is in viewport on scroll

Time:12-16

I'm trying to find an easy solution for my Angular App to check if an element is visible on scrolling and if it is then fire some animations. So, normally I just use jQuerys Waypoint Plugin. but it's not really the Angular Way. After Trying it from different angles, I came accross this npm package right here: ngui/common

The ngui-inview directive is exactly what I'm looking for but the documentation sucks really bad. Its just showing how I can lazy load images... that's not what I want.

Does anyone here has some experience using this package? I really need some help here

CodePudding user response:

Use intersection observer:

    // the element that you are observing (just add #yourElement in the template) for this  query to work
    @ViewChild('yourElement') yourElement: ElementRef;

    ngAfterViewInit() {
        const threshold = 0.2; // how much % of the element is in view
        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach((entry) => {
                    if (entry.isIntersecting) {
                        // run your animation code here
                        observer.disconnect(); // disconnect if you want to stop observing else it will rerun every time its back in view. Just make sure you disconnect in ngOnDestroy instead
                    }
                });
            },
            { threshold }
        );
        observer.observe(this.yourElement.nativeElement);
    }

There is no need for any additional packages/dependencies this feature is native to most modern browsers now.

See https://caniuse.com/intersectionobserver

More details: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

  • Related