I am new to angular 8 & created SPA(single page application), For menu bar separate component and that included inside home component. Whenever menu item clicked(Anchor element), it should scroll to about/contact element section, but I tried few solutions, but not able to scroll. Mainly parent elements are not accessible.
home.component.html
<app-header></app-header>
....
<section #aboutus>About us details</section>
....
<section #contact>Contact form section</section>
header.component.html
<ul>
<li class="nav-item">
<a (click)="navigateTo('aboutus')" ><strong>ABOUT</strong></a>
</li>
<li class="nav-item">
<a (click)="navigateTo('contact')" ><strong>Contact us</strong></a>
</li>
</ul>
header.component.ts
navigateTo(element: string) {
document.querySelector(''+element+'').scrollIntoView(true);
}
I am getting an error:
ERROR TypeError: Cannot read property 'scrollIntoView' of null
It will be great help.
Try like this:
home.component.html
<app-header (Navigate)="navigateTo($event)"></app-header>
home.component.ts
@ViewChild("aboutus", { static: false }) aboutus;
@ViewChild("contact", { static: false }) contact;
navigateTo(element: string) {
this[element].nativeElement.scrollIntoView({ behavior: "smooth" });
}
header.component.ts
@Output() Navigate = new EventEmitter();
navigateTo(element: string) {
this.Navigate.emit(element)
}
header.component.html
<ul>
<li class="nav-item">
<a (click)="navigateTo('aboutus')" ><strong>ABOUT</strong></a>
</li>
<li class="nav-item">
<a (click)="navigateTo('contact')" ><strong>Contact us</strong></a>
</li>
</ul>