I am using the scrollIntoView method on an element inside the ngAfterViewInit lifecycle hook. If I start debugging I can see that the scroll actually does its job initially but then the page gets reset and scrolled to the top afterwards.
Example:
items = [];
constructor(private elementRef: ElementRef) {
for(let i = 0; i < 100; i++) {
this.items.push("Item " + i);
}
}
ngAfterViewInit(): void {
this.elementRef.nativeElement.querySelectorAll('p')[71].scrollIntoView()
}
<p *ngFor="let item of items;">
{{item}}
</p>
Things that fix this but are not ideal for my case:
- Using `{behavior: 'smooth'} on the other hand works fine but I don't want to use that in my case.
- Executing the scrollIntoView inside a setTimeout(() => scrollIntoView, 100) works but feels hacky?
Any ideas as to why this is happening and if the setTimeout is the best solution or not?