I've been building a new site using Angular 4 and i'm trying to re-create a effect where when a div becomes visible (when you scroll down the screen) then that can then trigger a angular animation to slide the div in form the sides.
I've been able to do this in the past using jQuery outside of Angular 4 but i want to try and create the same effect using native Angular 4 animations.
Can anyone offer me advice on how to trigger an animation when a div comes into view (i.e. scrolled down to lower part of the page as it enters the viewport?). I have written the slide animations already but i don't know how to trigger that with a scroll when a div becomes visible at a later date to the view port.
Thanks everyone!
Here is a simple example of an infinity scroll; it triggers
handleScrollEvent()
when the element comes inside the viewport.inside
item-grid.component.html
inside
item-grid.component.ts
:I've created a base component that provides a flag appearedOnce, which turns true once if the component is either completely within view or it's upper edge has reached view's upper edge.
You can simply extend this component and make use of the appearedOnce property by inheritance
Keep in mind to call super() if you need to overwrite constructor or lifecyclehooks.
(edit) plunker: https://embed.plnkr.co/yIpA1mI1b9kVoEXGy6Hh/
(edit) i've turned this into a directive in another answer below.
A simple way if you want it in a specific component:
And in html:
Exactly when the top of the element is scrolled to the function is called. If you want to call the function only when the full div is in view add the div height to
this.chatTeaser.nativeElement.offsetTop
.I've created a directive that emits an event as soon as the element is either completely within view or it's upper edge has reached view's upper edge.
Here's a plunker: https://embed.plnkr.co/mlez1dXjR87FNBHXq1YM/
It's used like this:
Here's the directive: