4

I want to scroll down to a section when the page loads in Angular on some condition.

Please note: I want to scroll down without clicking on anything(i.e, on ngOnInit).

I tried this: in my component.html file

<div #sectionSubscribe>
    HTML...
</div>

in my component.ts file

ngOnInit(){
    this.scrollToSubscribe(sectionSubscribe);
}
scrollToSubscribe($element){
    $element.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest'
    });
}

But it doesn't allow me to do so. Please help

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
Mohit Pandey
  • 133
  • 1
  • 5
  • 17

1 Answers1

6

Try like this:

@ViewChild("sectionSubscribe", { static: true }) sectionSubscribeDiv: ElementRef;

scrollToSubscribe(){
    this.sectionSubscribeDiv.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });
}

Working Demo

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79