Menu Close

How to scroll to element on click in Angular and TypeScript?

To scroll to element on click in Angular and TypeScript, we call the scrollIntoView method.

For instance, we write

<button (click)="scroll(target)">Scroll To Div</button>
<div #target>Your target</div>

to add a button and a div in the template.

Then we write

//...
export default class Component {
  //...
  scroll(el: HTMLElement) {
    el.scrollIntoView();
  }
}

to add the scroll method into the Component component.

We call el.scrollIntoView to scroll to the el element, which is the div.

Posted in Angular, Angular Answers