Scroll to element on click in Angular 4

后端 未结 12 1027
逝去的感伤
逝去的感伤 2020-11-29 18:57

I want to be able to scroll to a target when a button is pressed. I was thinking something like this.

12条回答
  •  孤城傲影
    2020-11-29 19:17

    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:

    
    
    some code
    scrollTo(className: string):void { const elementList = document.querySelectorAll('.' + className); const element = elementList[0] as HTMLElement; element.scrollIntoView({ behavior: 'smooth' }); }

    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:

    
    

提交回复
热议问题