Scrolling to specific sections in Angular to dynamically add classes

In my Angular-based single page application (SPA), I am looking to dynamically add a class to the navigation menu whenever the user reaches a specific section. After exploring various options, I found a potential solution demonstrated in this StackBlitz example.

Check out the solution on StackBlitz here

Answer №1

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Change the CSS hover menu to function as a click menu instead of a hover

I am working on a CSS/HTML menu that includes the following CSS code: #nav { background-color:#F36F25; margin:0 0 5px 0; width: 100%; height:35px; left:0; z-index:1; border-top:2px solid #FFFFFF; border-bottom:2px solid #FF ...

Problem arises when combining string manipulation and piping operations

I have an HTML code within an Angular 2.0 template that looks like this: <span> Total Employee {{employeeCount> 0 ? '(' + employeeCount+ ')' : ''}} ></span> My customFormatter function is able to take a val ...

Can we refactor by using a distinct function?

I'm working on a table component that handles several columns in a similar way. I'm wondering if there is a more efficient way to optimize this code, perhaps by creating a separate function for it? import useTableStyles from 'admin/compo ...

Upgrading Xeditable button designs using AngularJS

Have a query. Can you replace the save(submit) button and cancel buttons with links in Xeditable for AngularJS? Appreciate your help ...

TypeScript's typeof operator in Angular functions allows you to check the

I am confused by a situation where I have a function with a typed parameter. Despite specifying the type as 'number', when I check the type of the parameter, I get "string" instead. How is this possible? Shouldn't it be strictly typed as &ap ...

Currently, I am working on developing a to-do task manager using Angular 2. One of the tasks I am tackling involves updating the value

I'm facing an issue with managing to-do tasks. I would like to update the value of an option in a select dropdown when the (change) event is triggered. There are 2 components: //app.component.ts //array object this.dataArr[this.counter] = {id: this ...

The property is not found in the '{}' type but is necessary in the type... Typescript connect strategy

Hello, I am currently trying to establish a connection pattern for React with TypeScript. I have a reducer set up as follows: type State = { version: number, a?: string } interface ActionC { type: string payload?: number } type IAction = Action ...

Angular - How child components can communicate with their parent components

I'm struggling to understand how to communicate between components and services. :( Even though I've read and tried a lot, some examples work but I still don't grasp why (?). My goal is to have one parent and two child components: dashboa ...

Tips for transferring information between two components when a button is clicked in Angular 2

I am currently working on a code that displays a table on the main page with two buttons, "Edit" and "Delete", for each row. When the Edit button is clicked, a modal opens up. My question is, how can I pass the "employee id" of a specific employee to the ...

Styling with react-jss based on intricate conditionals

After experimenting with react-jss for a few weeks, I am faced with the challenge of styling components efficiently. With numerous conditionals in these components, I am striving to avoid creating an excess of new components that essentially share the same ...

The pseudo-element ::after will not be positioned below the specified element

https://i.sstatic.net/Dd7mO.pngI am trying to position the grey vertical line below the text "latest work". However, when I set the z-index to negative, it disappears. I believe it is going under the body. Is there a simple solution to this? Attached is an ...

The CSS selector for radio input does not match when checked in IE7

I've been attempting to add a style to the label for a radio button with the CHECKED attribute, but so far all my attempts have failed to match on IE7. For example, I have created a JSFiddle here: JSFiddle. <!DOCTYPE html> <html> < ...

Troubleshooting a dynamically loaded Angular 2 module in Chrome and VS Code

Currently, I am utilizing WebPack in conjunction with Angular 2/4 and incorporating modules that are lazy loaded. Due to this setup, the components and modules are not included in the primary .js file; instead, their code is distributed across files genera ...

Responsive design in Bootstrap(-Vue) with compact input fields

I am currently working on creating an input form with small fields and signs between them. https://i.sstatic.net/THjhs.png Right now, I am using a combination of classic HTML and Bootstrap-Vue, as shown in the screenshot. It is functional, but the issue ...

Using jquery and css to allow hover effects and modify the color of active tabs

I need to modify the appearance of a tab in my left navigation menu so that it changes color when hovered over and remains that color when selected. I have limited experience with jQuery and CSS, so any guidance would be greatly appreciated! Below is the ...

Looking for a way to toggle the visibility of a dropdown list when clicking on an input in Angular7?

My Angular7 application features a dropdown menu that automatically closes when an item is selected. Additionally, I have implemented functionality to toggle the dropdown open and closed by clicking on an input field. You can view a live example of this be ...

Problems with scrolling in the navigation bar, main content area, and footer

The challenge Encountering a scrolling anomaly with the Navigation Bar, Body, and Footer while utilizing Bootstrap 4. Everything appears to function smoothly on the desktop view. The glitch arises when I reduce the viewport size. The body fails to stay in ...

A generic TypeScript with the ability to extend optionally

How can I modify the generic ApiResBook type to handle optional props with input check using the extends keyword? Sandbox. I have these main types defined, which correspond to fields in a database: // Main types as in database - should't be changed ...

Creating a personalized design for Bootstrap Badge

Looking to customize the shape of bootstrap badges from the default ellipse to a rectangle with rounded corners. Any tips on the best approach to accomplish this? ...

There are certain CSS3 properties that are not being accounted for in the CSS min

I've incorporated several newer CSS3 properties in my stylesheet, but I'm concerned that the minification tool I'm currently utilizing may not be capturing all of these properties: .big-blue-button:hover { text-decoration: none; bac ...