Scroll to element on click in Angular 4

JavascriptHtmlAngularTypescript

Javascript Problem Overview


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

<button (click)="scroll(#target)">Button</button>

And in my component.ts a method like.

scroll(element) {
    window.scrollTo(element.yPosition)
}

I know that the code above is not valid but just to show what I was thinking. I've just started to learn Angular 4 with no previous experience of Angular. I've been searching around for something like this but all the examples are in AngularJs which differs alot to Angular 4

Javascript Solutions


Solution 1 - Javascript

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?

Solution 2 - Javascript

In Angular 13 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'});
}

Solution 3 - Javascript

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();
}

Solution 4 - Javascript

There is actually a pure javascript way to accomplish this without using setTimeout or requestAnimationFrame or jQuery.

In short, find the element in the scrollView that you want to scroll to, and use scrollIntoView.

el.scrollIntoView({behavior:"smooth"});

Here is a plunkr.

Solution 5 - Javascript

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:

<button (click)="scrollTo('.footer')">ScrolltoFooter</button>
<footer class="footer">some code</footer>

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:

<app-footer class="footer"></app-footer>

Solution 6 - Javascript

Another way to do it in Angular:

Markup:

<textarea #inputMessage></textarea>

Add ViewChild() property:

@ViewChild('inputMessage')
inputMessageRef: ElementRef;

Scroll anywhere you want inside of the component using scrollIntoView() function:

this.inputMessageRef.nativeElement.scrollIntoView();

Solution 7 - Javascript

You can scroll to any element ref on your view by using the code block below. Note that the target (elementref id) could be on any valid html tag.

On the view(html file)

<div id="target"> </div>
<button (click)="scroll()">Button</button>
 

  

on the .ts file,

scroll() {
   document.querySelector('#target').scrollIntoView({ behavior: 'smooth', block: 'center' });
}

Solution 8 - Javascript

In Angular you can use ViewChild and ElementRef: give your HTML element a ref

<div #myDiv > 

and inside your component:

import { ViewChild, ElementRef } from '@angular/core';
@ViewChild('myDiv') myDivRef: ElementRef;

you can use this.myDivRef.nativeElement to get to your element

Solution 9 - Javascript

You can achieve that by using the reference to an angular DOM element as follows:

Here is the example in stackblitz

the component template:

<div class="other-content">
      Other content
      <button (click)="element.scrollIntoView({ behavior: 'smooth', block: 'center' })">
        Click to scroll
      </button>
    </div>
    <div id="content" #element>
      Some text to scroll
</div>

Solution 10 - Javascript

If the scroll goes too far

Get correct y coordinate and use window.scrollTo({top: y, behavior: 'smooth'})

Set different y coordinate if using multiple elements

Html file

<div class="sub-menu">
  <button (click)="scroll('#target1', -565)">Target One</button>
  <button (click)="scroll('#target2', -490)">Target Two</button>
</div>

<div>
  <div id="target1">Target One</div>
</div>

<div>
  <div id="target2">Target Two</div>
</div>

ts file

  scroll(elem: string, offset: number) {
    const yOffset = offset;
    const element = document.querySelector(elem)!;
    const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;

    window.scrollTo({ top: y, behavior: 'smooth' })
  }

Solution 11 - Javascript

I need to do this trick, maybe because I use a custom HTML element. If I do not do this, target in onItemAmounterClick won't have the scrollIntoView method

.html

<div *ngFor"...">
      <my-component #target (click)="clicked(target)"></my-component>
</div>

.ts

onItemAmounterClick(target){
  target.__ngContext__[0].scrollIntoView({behavior: 'smooth'});
}

Solution 12 - Javascript

I have done something like what you're asking just by using jQuery to find the element (such as document.getElementById(...)) and using the .focus() call.

Solution 13 - Javascript

You can do this by using jquery :

ts code :

    scrollTOElement = (element, offsetParam?, speedParam?) => {
    const toElement = $(element);
    const focusElement = $(element);
    const offset = offsetParam * 1 || 200;
    const speed = speedParam * 1 || 500;
    $('html, body').animate({
      scrollTop: toElement.offset().top + offset
    }, speed);
    if (focusElement) {
      $(focusElement).focus();
    }
  }

html code :

<button (click)="scrollTOElement('#elementTo',500,3000)">Scroll</button>

Apply this on elements you want to scroll :

<div id="elementTo">some content</div>

Here is a stackblitz sample.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser7136957View Question on Stackoverflow
Solution 1 - JavascriptFrank ModicaView Answer on Stackoverflow
Solution 2 - JavascriptRobert S.View Answer on Stackoverflow
Solution 3 - JavascriptLH7View Answer on Stackoverflow
Solution 4 - JavascriptJonView Answer on Stackoverflow
Solution 5 - JavascriptStephen E.View Answer on Stackoverflow
Solution 6 - JavascriptSchnapzView Answer on Stackoverflow
Solution 7 - JavascriptIfesinachi BryanView Answer on Stackoverflow
Solution 8 - JavascriptM.AmerView Answer on Stackoverflow
Solution 9 - JavascriptAndres GardiolView Answer on Stackoverflow
Solution 10 - JavascriptHarveyView Answer on Stackoverflow
Solution 11 - JavascriptSimoneMSRView Answer on Stackoverflow
Solution 12 - JavascriptKenneth SalomonView Answer on Stackoverflow
Solution 13 - JavascriptGnsView Answer on Stackoverflow