I want to be able to scroll to a target when a button is pressed. I was thinking something like this.
<button (click)="scroll(#target)">Button</button>
And in my component.ts a method like.
scroll(element) {
window.scrollTo(element.yPosition)
}
I know that the code above is not valid but just to show what I was thinking. I've just started to learn Angular 4 with no previous experience of Angular. I've been searching around for something like this but all the examples are in AngularJs which differs alot to Angular 4
There is actually a pure javascript way to accomplish this without using
setTimeout
orrequestAnimationFrame
or jQuery.In short, find the element in the scrollView that you want to scroll to, and use
scrollIntoView
.el.scrollIntoView({behavior:"smooth"});
Here is a plunkr.
Little late to this party, but I've written a plugin for Angular 4+ that does just this. It covers other issues you may bump into, like Server-Side Rendering. You can also animate to scrolling to your likings. Full disclosure, I'm the author.
NPM: @nicky-lenaers/ngx-scroll-to
GitHub: @nicky-lenaers/ngx-scroll-to
Hope this helps you out!
I have done something like what you're asking just by using jQuery to find the element (such as document.getElementById(...)) and using the .focus() call.
Jon has the right answer and this works in my angular 5 and 6 projects.
If I wanted to click to smoothly scroll from navbar to footer:
Because I wanted to scroll back to the header from the footer, I created a service that this function is located in and injected it into the navbar and footer components and passed in 'header' or 'footer' where needed. just remember to actually give the component declarations the class names used:
here is how I did it using angular 4.
Template
add this function to the Component.
Another way to do it in Angular:
Markup:
Add ViewChild() property:
Scroll anywhere you want inside of the component using scrollIntoView() function: