Reputation: 2913
I'm working on an Angular 10 project. I have a button in the footer component. I want to make the browser scroll to top page. I've searched how to do it on the internet and found that I can user a window.scroll(0,0); function. But There is nothing happens when I clicked on the button.
Below is my template code,
<footer>
<div>
<a class="footer_logo" (click)="scrollToTop()">
<img src="./assets/images/logo.png"/>
</a>
</div>
</footer>
And here is my footer.component.ts
scrollToTop(){
console.log("scroll to top !");
window.scroll(0, 0);
}
Please help.
Upvotes: 2
Views: 2877
Reputation: 27303
Use ViewPortScroller service.Which provide scrollToPosition method, You can that to scroll to specific position.
footer.component.ts
constructor(private vps:ViewportScroller){
}
scrollToTop() {
this.vps.scrollToPosition([0,0]);
}
Upvotes: 3
Reputation: 1363
In Angular, you can try the following :
<div #target>Your target</div>
<div>
<a class="footer_logo" (click)="scrollToTop(target)">
<img src="./assets/images/logo.png"/>
</a>
</div>
Then, in your component, just pass the element to which you want to scroll
scrollToTop(el: HTMLElement) {
el.scrollIntoView();
}
You can reuse this code and scroll anywhere you desire.
Cheers!!
Upvotes: 2