I have an Angular 8 SPA with a fixed-top navbar to auto-scroll the user to the section he clicked.
In the first place, I used a simple href="#section1"
. When the user clicks on a link in the navbar, the associated section is displayed properly. But I wanted to make it smooth, so I decided to use the scrollIntoView
method instead as shown here.
Unfortunately, it doesn't seem to work. The method scrollToElement()
is in the navbar component
and the target section is in another component (for the moment, the app component
, but this will change in future...). Because the anchor is in another component, when I click <a>
, the element is undefined and I get this error in the console : ERROR TypeError: Cannot read property 'scrollIntoView' of undefined
app.component.html
...
<div #section1></div>
<div #section2></div>
<div #section3></div>
<div #section4></div>
...
navbar.component.html
...
<li class="nav-item">
<a (click)="scrollToElement(section1)" class="nav-link">Section1</a>
</li>
...
navbar.component.ts
...
scrollToElement($element: any): void {
console.log($element); //returns undefinded
$element.scrollIntoView({ //throws an error because $element is undefined
behavior: "smooth",
block: "start",
inline: "nearest"
});
}
...
I think I am getting the problem, but I don't understand how to solve it. Should I use a variable in the navbar.component.ts
to store the element before using the scrollIntoView
method ?
Thanks in advance for your help!
SOLVED
navbar.component.html
...
<li class="nav-item">
<a (click)="scrollToElement('#section1')" class="nav-link">Section1</a>
</li>
...
navbar.component.ts
...
scrollToElement(selector) {
const element = document.querySelector(selector)
element ? element.scrollIntoView({behavior: "smooth"}): null;
}
...