Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2. How to detect if component is currently in viewport

I'd like to detect if the component position. Is currently in a view port and if yes run the trigger which stats an animation on this particular component.

I can't find any "angular" way to do it.

Example app( main component) every div is a separate component of app:

<div id="one">ww</div>
<div id="two">aa</div>
<div id="three">rr</div>
<div id="four">asf</div>
<div id="five">Something...</div>
<div id="six">rq</div>

So... I'd like to detect when component five is in viewport (present on a screen) and start animate that component.

Any ideas?

Thanks

like image 456
Radek Avatar asked Dec 23 '16 13:12

Radek


People also ask

How to know if an element is in the viewport?

If an element is in the viewport, it's position from the top and left will always be greater than or equal to 0 . It's distance from the right will be less than or equal to the total width of the viewport, and it's distance from the bottom will be less than or equal to the height of the viewport.

How to check if a div is in viewport?

Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.

What is angular viewport?

Angular Data Grid: Viewport Row Model. A Viewport is a row model that allows showing a 'window' of data in your client. Typically all the data will reside on the server and the server will know what data is displayed in the client.


1 Answers

You could use the ng-in-viewport plugin.

HTML:

<div id="five" in-viewport (inViewportAction)="action($event)">Something...</div>

Component:

action(event : any){
    if(event.value){
       //Do something here (e.g apply CSS class to start the animation)
    }
}

Check my detailed answer on a similar question here.

like image 138
adrianmanduc Avatar answered Oct 03 '22 05:10

adrianmanduc