0

I have a form where I am adding objects to An array, then I am giving the user a preview of the created objects.

I am looping the array with a *ngFor and each element added to the bottom of the screen. My goal that after each element was added there will be an auto scroll to the bottom of the page

Currently i am using a setTimeOut function, but i was wondering is there a better way?

this.createdAppointments.push(appointmentFormValues);

    setTimeout(() => {
      window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
    }, 1);
Igor.R
  • 175
  • 4
  • 14
  • why do you even need the timeout? You could create some kind of "scrollOnAppearance" directive which implemented this logic for you to enforce single responsibility and resuability principles. – bryan60 Jan 13 '19 at 20:04
  • @bryan60 I created a directive but the page don't scroll to the all bottom. `import {Directive} from '@angular/core'; @Directive({ // tslint:disable-next-line:directive-selector selector: '[AutoScrollDown]' }) export class AutoScrollDownDirective { constructor() { window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight); } }` – Igor.R Jan 13 '19 at 20:15
  • do it in afterViewInit instead of the construtor or add a delay of a few ms – bryan60 Jan 13 '19 at 20:16
  • Great! Thank you @bryan60 – Igor.R Jan 13 '19 at 20:18
  • Possible duplicate of [Angular: unable to scroll down to bottom in element](https://stackoverflow.com/questions/53123912/angular-unable-to-scroll-down-to-bottom-in-element) – ConnorsFan Jan 13 '19 at 20:34

1 Answers1

1

You can call scrollIntoView method on newly added items, see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView