Issue
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.
Solution
Not sure what is your question.
If you asking why you need setTimeout it's because you need to fire your scroll at the end of the dom rendering.
You could also just use setTimeout(()=>{...})
without value at all, it's working also
For the smoothness of the scroll, you can't achieve it through behaviour:smooth
since it's only supported by mozilla browser!
The response sadly is that you can't achieve this straighforward with angular2.
I use ionic and they have a very good .scrollTo
functionalities on their content.
@ViewChild(Content) content: Content;
public scrollToResults() {
setTimeout(() => {
let element = document.getElementById('myElement');
//1000 is the scroll time it self, 1s:
this.content.scrollTo(0, element.offsetTop, 1000);
})
}
If you don't use ionic you can reproduce how they accomplish it https://github.com/ionic-team/ionic/blob/master/src/util/scroll-view.ts
I dont't think it's worthing to import ionic if you don't use it. Maybe only importing ionic-angular
would be enough, you don't need to import everything.
Answered By - David Faure
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.