Categories
Angular Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *