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

malbarmavi
  • 18,795
  • 4
  • 45
  • 73
MoHiT PaNdEy
  • 139
  • 15

1 Answers1

4

Try like this:

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

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

Working Demo

Adrita Sharma
  • 17,967
  • 8
  • 40
  • 61