Tips on applying the "activate" class to a Bootstrap navbar in Angular 2 when implementing page anchor navigation

As I work on my single-page website using Angular 2 and Bootstrap 4, I have successfully implemented a fixed navbar component that remains at the top of the page. Utilizing anchor navigation (#id), the navbar allows smooth scrolling to different sections on the same page without needing a routing module.

The code for the navbar can be found below:

<nav class="navbar navbar-default fixed-top navbar-inverse navbar-toggleable-md">
  <div class="container">

    <div class="navbar-header">
      <button class="navbar-toggler navbar-toggler-right btn btn-outline-secondary" (click)="isCollapsed = !isCollapsed" [attr.aria-expanded]="!isCollapsed" aria-controls="collapseExample">
        <i class="fa fa-bars" aria-hidden="true"></i>
      </button>
      <a class="navbar-brand" href="index.html">Garatéa</a>
    </div>

    <div id="collapseExample" class="navbar-collapse collapse" [ngbCollapse]="isCollapsed">
      <ul class="nav navbar-nav ml-auto">
        <li class="nav-item"><a class="nav-link" href="#home">Home</a></li>
        <li class="nav-item"><a class="nav-link" href="#about">About</a></li>
        <li class="nav-item"><a class="nav-link" href="#team">Team</a></li>
        <li class="nav-item"><a class="nav-link" href="#contact">Contact</a></li>
      </ul>
    </div>
  </div>
</nav>

Each link within the navbar corresponds to a section on the website, such as the 'home' section template shown below:

<div id="home" class="text-center home-background">
  <div class="overlay">
    <div class="content">
      <h1>Welcome to <strong><span class="title-text">Garatéa</span></strong></h1>
      <p class="lead">We are an initiative that focuses on <strong>increasing survival rates</strong> in medical emergencies.</p>
    </div>
  </div>
</div>

I am seeking advice on how to dynamically highlight the corresponding link in the navbar based on the section of the website currently being viewed. For instance, when on the 'about' or 'team' section, I envision adding an active CSS class to the respective navbar link:

<li class="nav-item active"><a class="nav-link" href="#about">About</a></li>
.

Answer №1

To access the srcElement when clicking on an <a> tag, you can use the following method:

<a class="nav-link"(click)="clickedLink($event)">Início</a>
<a class="nav-link"(click)="clickedLink($event)">Início</a>
<a class="nav-link"(click)="clickedLink($event)">Início</a>

The function will look like this:

clickedLink(e){
let element = e.srcElement;

console.log(e)
for(let i=0; i <element.parentElement.children.length ; i++){
  if(element.parentElement.children[i].classList.contains('active')){
    element.parentElement.children[i].classList.remove('active')
  }
}
element.classList.add('active');

}

SEE LIVE DEMO

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

React Scroll and Material-UI button active link not functioning correctly

Whenever the link goes to the correct page, I want to add a special background effect or change the font color. Despite trying to use CSS for this purpose, it didn't work as intended. If you want to take a look at my code on codesandbox, follow this ...

Leveraging Ajax XHR2 for uploading files and accessing values in PHP

I recently followed a fantastic tutorial online on how to use AJAX to upload a file in an HTML form. Here is the code snippet I used: HTML <input type="file" id="myFile" name="myFile" /> <input type="button" id="upload" value="upload" /> < ...

changing the breadcrumb item to a dropdown item in a dynamic way

Hey there, I'm currently working on creating a breadcrumb item using Angular. Here is what I have so far: https://i.stack.imgur.com/zt5yX.png I decided to add a dropdown for the breadcrumb item, but I'm facing a challenge: I want to be able to ...

Learn how to retrieve data outside of the .subscribe function in an Angular 2 polling service

// I'm facing an issue where I am unable to assign values from outside the subscribe function to any variable. In my current project, I am fetching JSON content using the http.post() method and storing it in a variable. However, I need to access this ...

Necessary form group in html [Angular]

Is there a way to make certain form fieldsets required while allowing the user to choose which inputs to fill? My idea: Users can select what they want to fill out without having to complete all of the fieldset inputs. I have these two options: 1: < ...

Which web browser(s) can properly display the CSS property display: run-in?

Compatibility with IE7 and FF2.0 Suitable for IE8 and Opera 9+ Works only on IE7 Optimized for IE8 and FF3.5 Supports IE7 and Safari This question came up in a quiz, but I don't have all the browsers to test it. Any assistance would be greatly apprec ...

The HTML content I created is too large for the screen and is extending beyond its borders

The navigation bar and footer on my HTML page adjust themselves according to the screen width, but the main content is not adjusting properly. I tried using a media query for mobile resolution (517px), but when I tested it on a PC with a smaller screen wi ...

Steps to insert a style tag into the head using an AngularJS directive

Greetings! Users have the option to choose between printing reports in landscape or portrait format. I am interested in finding out if it is feasible to incorporate the following code snippet into the header of a web document using an AngularJS directive. ...

Application utilizing electron technology featuring various tabbed browsing windows connecting to secure websites

Currently, I am in the process of developing my own unique version of a platform similar to using Electron technology. The objective for this app is to provide users with the ability to view multiple URLs simultaneously, such as and , through a tabbed i ...

Apply a patterned background with CSS styling

I have tried to implement a custom CSS design using the background image bg.jpg with a pattern of dots.png that repeats both horizontally and vertically. *{ margin: 0; padding: 0; } body { margin: 0px; padding: 0px; color: #666; fo ...

Border extends across two separate rows

Let me illustrate my issue with a specific example where I am utilizing a single column with a rowspan: <table border="1" style="width:300px"> <tr> <td rowspan="2">Family</td> <td id="jill">Jill</td> <td>Smi ...

Return the reference to an injected service class from the location where it was implemented

Is it feasible to return a reference from a component class with a custom interface implemented to the injected service class in my Angular 6 project? Here is an example of what I am aiming for. ServiceClass @Injectable() export class MyService { co ...

What steps can be taken to solve the JavaScript error provided below?

My objective is to create a new variable called theRightSide that points to the right side div. var theRightSide = document.getElementById("rightSide"); Once all the images are added to the leftSide div, I need to use cloneNode(true) to copy the left ...

What are the solutions for addressing popping behavior during hover effects?

Hello everyone, I am experiencing an issue with the image hover effect on my website. How can I make it enlarge smoothly instead of just fading in and out? To better demonstrate, I have provided a helpful example https://i.stack.imgur.com/TcZKy.jpg Any as ...

Clean coding techniques for toggling the visibility of elements in AngularJS

Hey everyone, I'm struggling with a common issue in my Angular projects: app.controller('indexController', function ($scope) { scope.hideWinkelContainer = true; scope.hideWinkelPaneel = true; scope.headerCart = false; scope. ...

Using Selenium 2 to dynamically insert CSS styles into the currently visible webpage

I experimented with using jQuery on a webpage that has already been modified by jQuery in order to add custom CSS code: jQuery('head').append('<style type=\"text/css\">body { background: #000; }</style>'); When I ...

Using CSS to create a triangular background within a <div> element

I am looking to create a CSS triangle shape for a background, but I am unsure of how to achieve this or if it is even possible. Ultimately, I want the menu to resemble the image linked below: While I have come across methods to create the desired shape, ...

Navigating the bitbucket pipeline to execute test cases for Angular 4 applications

Currently, I am facing an issue while integrating Bitbucket Pipeline for Angular 4. The problem lies in the fact that Chrome browser is not opening in the Bitbucket Pipeline console. My main objective is to figure out a way to execute test cases in the B ...

Tips for positioning label/input box/button on Internet Explorer 7

Here is a Fiddle example you can check out, along with the corresponding code : <div class="menu-alto"> <ul> <li> <a title="Link" href="#">Link</a> </li> <li class="newsletter ...

Ways to position a flexbox child at the bottom of its container

Utilizing Flexbox to arrange different content in a panel, there is an issue with the positioning of icons within each panel. The fourth icon wraps around and aligns with the first one at the top of its container, instead of lining up with the third icon a ...