How do I auto scroll in Angular?

10,487

There is no automatic feature to auto scroll a div when the size changes.
I suppose you dynamically add your cards using some button? Then you could scroll programatically when adding a card!

Here are multiple suggested solutions:

  • You can use jquery's method "scrollLeft()". Just set the horizontal scroll to something like 99999 to be sure it goes as far possible.
  • Change the default scrollTo() behavior of your html element (see this thread).
  • Use the css directive direction: rtl to set the default scroll bar position to the right (see this thread)

Here is an example using the solution 2) : https://angular-dfjmej.stackblitz.io

Maybe it's not the exact render you want, but it's only a matter of settings then.

Share:
10,487
Michael
Author by

Michael

Updated on June 04, 2022

Comments

  • Michael
    Michael almost 2 years

    I got a dynamic component, where I add material cards horizontally. After a few cards, the component gets filled, and I can scroll the component. But how can I make it auto scroll horizontally, so that I don't have to use the mouse all the time?

    I already tried playing with some css attributes like overflow and so on.

    .blocksWrapper {
      display: flex;
      overflow: auto;
      min-height: 305px;
    }
    

    I expect, that it autoscrolls horizontally.

    This is how it should look like:

    enter image description here

    But instead it never scrolls automatically.

    • Admin
      Admin over 5 years
      Can you please clarify- do you mean so that you don't have to click the scrollbar with the mouse, or are you trying to have the code do some auto scrolling? If the mouse is the problem, shift + scroll wheel is horizontal, or most trackpads support the multi touch gesture.
    • Michael
      Michael over 5 years
      No. What I mean: The component always stays at the same spot, even when I add more cards. What I want: It should always scroll to the right automatically, so that the most recent card gets shown. But of course scrolling with the mouse should be possible too. I hope you know what I mean.
    • Admin
      Admin about 5 years
      I was looking at this stackblitz stackblitz.com/edit/… from this answer stackoverflow.com/questions/43945548/…, can you have a no size element after that you always call scrollIntoView on when you add a card?
  • Michael
    Michael over 5 years
    How do I use scrollLeft() in TypeScript? Can you give me an example?
  • Kapcash
    Kapcash over 5 years
    I edited my answer with a stackblitz link where you can find a solution.