This is supposed to be very simple, I have a certain element in my component template that I want to scroll down to it smoothly after the page finishes loading if it is passed in the url as a fragment like this: '../componentPath#someElement'
I tried to do it by adding a #someElement to the element in html and then used
@ViewChild('someElement') someElement: ElementRef
then called the ngAfterViewInit() like this:
ngAfterViewInit() {
this.route.fragment.subscribe((fragment: string) => {
if (fragment === 'someElement') {
this.someElement.nativeElement.scrollIntoView({behavior: 'smooth', block: 'start'});
}
});
}
But nothing happens, it works perfectly if I call the scrollIntoView() after some short period using setTimeOut() like this:
ngAfterViewInit() {
this.route.fragment.subscribe((fragment: string) => {
if (fragment === 'someElement') {
setTimeout(() => {
this.servicesSection.nativeElement.scrollIntoView({behavior: 'smooth', block: 'start'});
}, 1000)
}
});
}
Of course this is wrong, but it gave me the conclusion that my problem is with the time of firing the scrollIntoView() event.
I read many discussions on many sites and couldn't get it to work properly yet, so I thought it could be a good idea to open a question here.