To ensure proper functionality, it is important to query the HTML elements within the ngOnInit
lifecycle hook.
Include the following code snippet:
ngOnInit() {
this.sections = document.querySelectorAll('section');
this.navLi = document.querySelectorAll('nav .container ul li');
}
Once you have updated your code to the following:
import { Component, HostListener, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
sections: NodeListOf<HTMLElement>;
navLi: NodeListOf<HTMLElement>;
ngOnInit() {
this.sections = document.querySelectorAll('section');
this.navLi = document.querySelectorAll('nav .container ul li');
}
@HostListener('window:scroll', ['$event'])
onscroll() {
var current: any = '';
this.sections.forEach((section) => {
const sectionTop = section.offsetTop;
if (scrollY >= sectionTop - 60) {
current = section.getAttribute('id');
}
});
this.navLi.forEach((li) => {
li.classList.remove('active');
if (li.classList.contains(current)) {
li.classList.add('active');
}
});
}
}
Your desired behavior should now be achieved successfully.
For further information on the ngOnInit
lifecycle hook, refer to https://angular.io/guide/lifecycle-hooks