'Adding class by scrolling to certain sections angular

In my SPA build in Angular i want to add a class to the navigation every time the user arrives to a certain section. I have been trying the following solution as seen in this stackblitz.

https://stackblitz.com/edit/angular-ivy-gdxcw8?file=src/app/app.component.ts



Solution 1:[1]

You need to query the HTML elements in ngOnInit.

Add this:

  ngOnInit() {
    this.sections = document.querySelectorAll('section');
    this.navLi = document.querySelectorAll('nav .container ul li');
  }

After changing your code to:

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');
      }
    });
  }
}

I get your desired behaviour.

Read more about ngOnInit at https://angular.io/guide/lifecycle-hooks

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yifan Ai