0

Previous solution to similar StackOverflow question is focused on Jquery and no possible solution found for angular 6/Javascript.

Currently, I am using scrollIntoView() with behavior as smooth to scroll to a dynamically created div using router outlet, but it only scrolls after the second click, is there anything wrong in my code or is it possible to achieve it in the first click?

Html:

<div>
  <mat-card-title (click)="articleNavigation(documents._id)">{{documents.title}}</mat-card-title>
</div>
<div #test style="width:50%; margin-left: auto; margin-right: auto;">
  <router-outlet></router-outlet>
</div>

ts:

articleNavigation(documentId) {
 this.router.navigate(['./document' , documentId], { relativeTo: this.route });
 this.test.nativeElement.scrollIntoView({behavior: 'smooth'});
}

If I use behavior auto instead of smooth, it works on the first click, but a smooth transition is preferred. One of the possible reason which I think is on the first click, div is created and on the second click scrollIntoView() transits to the div.

Madhavan Sundararaj
  • 267
  • 1
  • 5
  • 17

1 Answers1

2

Try this :

setTimeout(() => {
    this.test.nativeElement.scrollIntoView({behavior: 'smooth'});
});
Cyril
  • 254
  • 1
  • 6