190

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

15
  • 1
    Your syntax does not have problems but you need to define what is #target.
    – wannadream
    May 12, 2017 at 19:58
  • 1
    So this should work? When I use a arbitrary number and call window.scrollTo(500) in my function nothing happens. I was thinking that element would be a HTMLElement
    – user7136957
    May 12, 2017 at 20:09
  • Right, however, what is #target, Angular will not resolve it? You can test scroll() with no parameter first.
    – wannadream
    May 12, 2017 at 20:19
  • Yeah I tried (click)="scroll()" in my button and window.scrollTo(0, 500) in the component but nothing happens
    – user7136957
    May 12, 2017 at 20:24
  • 3
    But when I do window.scrollTo(0, 500) in the constructor with a 500ms delay it works
    – user7136957
    May 12, 2017 at 21:08

16 Answers 16

242

You could do it like this:

<button (click)="scroll(target)">Scroll To Div</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?

16
  • 2
    @N15M0_jk Yep, there's also an object you can pass in with other options, depending on what you need. developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView Jul 10, 2017 at 12:57
  • 2
    @Anthony It allows you to reference the element that you want to pass to the scroll function on the component. Notice that the click event calls scroll(target). If you wanted to get access to the element from inside the component without having to pass the element in, you could use @ViewChild. Sep 19, 2017 at 15:42
  • 1
    Following link will be a right solution stackoverflow.com/questions/47616843/…
    – abbas-ak
    Mar 15, 2018 at 11:37
  • 4
    It works fine with me now. But before i made a silly mistake and used id="target" instead of #target and it gave me "el is undefined error"!
    – Yash
    Feb 7, 2019 at 12:18
  • 4
    I believe the undefined error happens if the element with the #target is inside an *ngIf, but it should work if you use the @ViewChild method in the link from @abbastec Dec 12, 2019 at 20:00
123

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'});
}
6
  • 21
    bonus for {behavior: 'smooth'} May 19, 2019 at 6:43
  • 1
    It's working for me.. special thanks for {behavior: 'smooth'} Oct 9, 2019 at 5:59
  • 4
    This will not work if #target is defined after the button, which is relevant if you have a floating header for example...
    – Jonathan
    May 16, 2020 at 2:57
  • Awesome, works for me too and appreciate the bonus of smooth scrolling Jun 24, 2021 at 16:44
  • 1
    This works perfectly. Bonus: el.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' }) --- worked better for me; To have a smooth transition & not scroll the whole page in the case of a side-navigation. Ref->stackoverflow.com/questions/11039885/… Feb 24, 2022 at 13:05
85

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();
}
7
  • 6
    You haven't set elementRefs or HTML ids in your template. Where exactly is the 'cat-'+cat.category_id element that you are scrolling to?
    – Keegan
    Apr 23, 2019 at 5:56
  • 1
    This is a better answer. You can put the scroll to another component. Aug 25, 2019 at 11:17
  • 1
    This should be the accepted answer. Working for Angular 9.
    – Sixteen
    Jun 14, 2020 at 20:54
  • Working in Angular 11 Apr 2, 2021 at 17:38
  • 1
    stackoverflow.com/a/36180398/1266873 in case you want it animated.
    – Koray
    Sep 28, 2022 at 9:02
58

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.

4
  • 3
    2 ways that this answer is different: 1. This is animated smooth scrolling, not a jump. 2. This answer does not scroll a window, but moves a scrollview within a window. For example, if you have a horizontal scrollview within the window. Check the plunkr for an example.
    – Jon
    Dec 11, 2017 at 19:51
  • 1
    scrollIntoView's scrollIntoViewOptions (the object as argument) is only compatible with Firefox right now. May 18, 2018 at 9:41
  • Works fine for Chrome and Firefox, but not for Safari. Jan 29, 2019 at 12:32
  • This worked for me in Angular 9 Aug 1 at 13:32
28

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

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>
1
  • In Angular 14 it works without the dot (click)="scrollTo('footer')"
    – Abid
    Aug 29, 2022 at 10:40
19

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' });
}
10

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

<div #myDiv></div> 

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

3
  • This is a good solution but problem is that it only works when i reload the tab but not with routerLink. Any solution for this problem guys ? Jul 1, 2020 at 11:06
  • how I can use a class with this? Nov 27, 2020 at 17:52
  • @Ahsan you might want to try ngAfterViewInit or ngAfterViewChecked.
    – Boat
    Mar 16, 2021 at 12:51
8

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>
0

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' })
  }
0

First, I tried the simplest solution, which was the use of DOM commands like Element.scrollIntoView(), or

document.getElementById("<yourTarget>").scrollIntoView({
  behavior: "smooth",
  block: "start",
  inline: "nearest"
});

(Remember to add id="<yourtarget>" where you want to scroll) It worked on development, and it was quite easy, but after deploying to production environment I noticed that the scroll was not working!

So, I tried another way, using Angular's ViewportScroller. In order to do that, you have to inject ViewportScroller at Component's constructor, like constructor(private scroller: ViewportScroller) and just call this.scroller.scrollToAnchor("<yourTarget>");. Again, no big deal, and again it was NOT WORKING on production environment.

The third way to do it, is to use Router to provide navigation to the anchor I wanted. Similarly to the last option, inject Router to constructor, like

constructor(private router: Router), and use the command: this.router.navigate([], { fragment: "<yourTarget>" }); Finally it DID WORK on production environment! I don't know for sure why the previous methods failed, I read some sources that says Angular Material blocks scrolling, but I'm not sure.

In order to present the different options there's a Stackblitz as an example.

https://stackblitz.com/edit/scrolling-types

There you can click on tree buttons, each one using a different method to scroll down to some anchor.

0

For me the top answer moved my entire component causing areas of the page to be blocked off. I fixed it by adding some additional properties

element.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' })
0

Angular 15:
I had an issue where scrolling was not working because I was using *ngIf directive with a variable that was updated at same time when I was triggering scroll. In one change detection, it did not update the variable, and that part of HTML did not exist, so I used setTimeout, to do the scrolling in another change detection.

<div  (click)="someVariable = true; scroll()">
<div *ngIf="someVariable" #menuHamburgerDiv>



@ViewChild('menuHamburgerDiv') menuDiv: ElementRef;
 
 scroll() {
    setTimeout(() => {
      this.menuDiv.nativeElement.scrollIntoView({ behavior: 'smooth' });
    }, 0);
  }
-1
    goToDIV() {
    
        document.getElementById('targetBlue').scrollIntoView({
          behavior: 'smooth',
          block: 'start',
          inline: 'nearest',
        });
      }

 <div id="targetBlue" >
    <h2 class=""><b>Blocage temporaire</b></h2>
 </div>
1
  • Please read How to Answer and edit your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post. Also, do not dump the same answers on multiple questions please. Instead. flag them for closure as a duplicate.
    – Adriaan
    Sep 18 at 11:08
-2

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'});
}
-21

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.

2
  • 2
    Except this op is asking for TypeScript solutions not work arounds with an obsolete framework (down voted)
    – Ash
    Jul 14, 2018 at 13:24
  • 3
    You’ve missed my point, your answer uses jQuery (might I add in the most inefficient way) rather than simply using ES*. Your constants don’t declare their type neither. It’s just a bad example with bad logic using jQuery which is not what was asked.
    – Ash
    Jul 25, 2018 at 19:51