0

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

1
  • Please prive code as text
    – Thibaud
    Mar 18, 2022 at 9:27

1 Answer 1

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.