I am trying to do a scroll to an anchor when I redirect to a new page. I have tried different things but without success. Now it scrolls down but it's not showing the whole HTML element I need, it shows only the header of the element. Here is the redirect to the new page
this.router.navigate(['/controllo/' + result.id], {fragment: 'assegnazioneContatto'});
And here is how I scroll to the element
ngOnInit() {
this.routeParams.fragment.subscribe(fragment => {
if(window.document.getElementById(fragment)) {
this.fragment = fragment;
window.document.getElementById(this.fragment).scrollIntoView();
}
});
}
Here is the HTML element
<div class="row" [hidden]="!showAssegnazioneContatto()" id="assegnazioneContatto"></div>
What am I doing wrong? I have seen other questions here in stackoverflow but I haven't found any solution.
PS. If I run the code in the console it works fine
From your question I have understood that the scroll is behaving in a way that it shows most of the preceding elements and the beginning of your new element.
Does this jsFiddle illustrate your situation? https://jsfiddle.net/eqzkpr8a/3/
Try playing around with the
scrollIntoView()'s options: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView#parameters. Specially the block property, which defines the vertical alignment of the page based on its ancestor element.In other words, the block property may have four possible values: start, center, end, and nearest. The properties align the page vertically