Reputation: 3489
I have sticky header when page is scrolled it is fixed at the top of the page.when I click on the menu in the header page must scroll to that particular div.For sticky header i am using angular.for scrolling normal java script window.scroll(). but window.scroll() not scrolling accurately.
//stickyheader.html
<div #stickyMenu [class.sticky]="sticky">
<div class="header">
<div class="navbar">
<ul>
<li><a>Home</a></li>
<li><a (click)="scrollTo('candidate')">Candidate</a></li>
<li><a (click)="scrollTo('client')">Client</a></li>
<li><a (click)="scrollTo('user')">User</a></li>
</ul>
</div>
</div>
</div>
//stickyhedaer.ts
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef, HostListener } from '@angular/core';
import { TargetLocator } from 'selenium-webdriver';
@Component({
selector: 'app-sticky-header',
templateUrl: './sticky-header.component.html',
styleUrls: ['./sticky-header.component.css']
})
export class StickyHeaderComponent implements OnInit, AfterViewInit {
@ViewChild('stickyMenu') menuElement: ElementRef;
sticky: boolean;
elementPosition: any;
myElement: ElementRef;
constructor() {
this.sticky = false;
}
ngAfterViewInit() {
this.elementPosition = this.menuElement.nativeElement.offsetTop;
console.log(this.menuElement);
}
@HostListener('window:scroll', ['$event'])
handleScroll() {
const windowScroll = window.pageYOffset;
if (windowScroll >= this.elementPosition) {
this.sticky = true;
console.log(this.elementPosition + ' host listener scroll');
} else {
this.sticky = false;
}
}
scrollTo(id: any) {
console.log(id);
id = document.getElementById(id);
// id.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' });
const yCoordinate = id.getBoundingClientRect().top + window.pageYOffset;
const yOffset = 70;
window.scroll({
top: yCoordinate - yOffset,
behavior: 'smooth'
});
}
}
//app.component.html
<div>
<div class="content"></div>
<app-sticky-header></app-sticky-header>
<app-candidate></app-candidate>
<app-client></app-client>
<app-user></app-user>
<div class="content"></div>
</div>
Upvotes: 0
Views: 361
Reputation: 587
I made a stackblitz example related to your query. In that header sticky and scrolling to that section is working properly. I didn't add multiple compnent. Instead of that i added text in
tag and gave same id to that section.
Upvotes: 1