Reputation: 752
I am sure i must be doing something wrong but can't figure out what. Need some help/pointers.
I am using Angular 10. I have enabled anchorScrolling in app-routing.module
const routes: Routes = [
{ path: 'docs', component: DocsComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes, {
useHash: true,
anchorScrolling: 'enabled'
})],
exports: [RouterModule]
})
export class AppRoutingModule { }
This works if the container for the jump-sections (the sections with #id where I want to scoll to) does not have property overflow:auto set , but if I set the property overflow:auto then the scrolling stops working through anchorScrolling. I can still scroll manually or by typing the url along with the fragment.
I have created a StackBlitz project to demonstrate this. The project here is working by default
https://stackblitz.com/edit/angular-ivy-ub5k7q
However if you add
overflow:auto
to the
.sections
class in the hello.component.css you will see that the section links give at the top don't result in scroll even though the url does get updated with the correct route#fragment.
Is this an expected behavior?
Upvotes: 4
Views: 3083
Reputation: 1784
According to this answer, I propose you a solution without fragment, but which works.
First change your a
element as follow <a (click)="toSection('1')">Section 1</a>
and for each section change the number with the corresponding one.
Then in your component add this method
toSection(section: string){
const elem = document.getElementById("section-"+section);
const topPos = elem.offsetTop
document.getElementById('sections').scrollTo({top:topPos-10, behavior:'smooth'})
}
With topPos-10
, you got something a bit more beautiful because the top of the div is not stick to the section title.
PS : This way, in my opinion, it's a little bit better because you don't have your URL with #section
at the end.
Here is the stackblitz.
Upvotes: 1
Reputation: 188
I couldn't figure out why this is happening. Tried for minutes, but I could get to what I believe was your objective in the first place.
The changes I made (only in hello.component.css):
.sections{
position:relative;
top:5rem;
border:2px solid rebeccapurple;
overflow:auto;
}
I removed the height you were setting up for the position property which had the value 'absolute'. I also changed the value from the position property to be relative.
It is working with the position set to be 'absolute', but whenever you apply values for width and height it stops working.
Upvotes: 2