Scroll to element on click in Angular 4
You could do it like this:
<button (click)="scroll(target)"></button><div #target>Your target</div>
and then in your component:
scroll(el: HTMLElement) { el.scrollIntoView();}
Edit: I see comments stating that this no longer works due to the element being undefined. I created a StackBlitz example in Angular 7 and it still works. Can someone please provide an example where it does not work?
Here is how I did it using Angular 4.
Template
<div class="col-xs-12 col-md-3"> <h2>Categories</h2> <div class="cat-list-body"> <div class="cat-item" *ngFor="let cat of web.menu | async"> <label (click)="scroll('cat-'+cat.category_id)">{{cat.category_name}}</label> </div> </div></div>
add this function to the Component.
scroll(id) { console.log(`scrolling to ${id}`); let el = document.getElementById(id); el.scrollIntoView();}
In Angular 7 works perfect
HTML
<button (click)="scroll(target)">Click to scroll</button><div #target>Your target</div>
In component
scroll(el: HTMLElement) { el.scrollIntoView({behavior: 'smooth'});}