Highlight the active class on the Angular Navbar

I have been successfully using [routerLinkActive]="['active']" in my application to add an active class when the button on navbar is clicked and redirects to example.com/home. However, I noticed that if I only navigate to example.com, the active class does not appear. This happens because both /home and the base URL are part of the same component. Does anyone know how I can resolve this issue?

Answer №1

To manage redirection in your routing module, you can use a redirect.

const routes: Routes = [
  { path: "", redirectTo: "home", pathMatch: "full" },
  { path: "**", component: PageNotFoundComponent, pathMatch: "full" }
];

Here's the explanation:

The redirect will send users from example.com to example.com/home. This way, the routerLinkActive will appropriately highlight the selected route.

Check out Angular Scaffolding for a demonstration of this method. Try removing the path and observe the difference.

A more effective approach is to monitor route events:

View Demo
Access Source Code

Consider implementing something like this:

constructor(
  private router: Router
) {
  router.events.subscribe((event: RouterEvent) => {
    this.navigationInterceptor(event);
  });
}

Follow up by implementing this logic:

navigationInterceptor(event: RouterEvent): void {
    if (event instanceof NavigationStart) {
      this.currentUrl = event.url;

      const route: Route = this.currentUrl;

      this.loading = true;
    } else if (
      event instanceof NavigationEnd ||
      event instanceof NavigationCancel ||
      event instanceof NavigationError
    ) {
      this.loading = false;
    }
  }

Utilize the route URL within your template, similar to this example:

<a mat-tab-link matFocus="true" *ngFor="let route of routes" [routerLink]="route.url" routerLinkActive [active]="currentUrl === route.url" (click)="currentUrl = route.url" #tabs>
     {{route.label | uppercase}}
</a>

Review the source code for further clarity on implementation.

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

You can submit a photo to a form as an attached file

I had a code that looked like this My goal is to simplify the process for users by allowing them to fill out additional information in a form without having to upload an image separately. I want to display the canvas image from the previous page in the fo ...

Ways to fetch additional Product Cards using JSON and a nextPage parameter

I'm facing difficulties in nesting a fetch inside another fetch. I'm not sure if this is the correct approach, but my goal is to utilize Vanilla JavaScript to fetch another JSON from the nextPage URL within the JSON list when the "load more" butt ...

Oops! Looks like the 'opennebula' module is missing in your Meteor.JS project

I've attempted using meteorhacks:npm but encountered the same issues. While working on a Meteor.JS application with iron:router installed, I'm facing difficulties loading the NPM module "opennebula" (found at https://github.com/OpenNebula/addon- ...

Sending a JSON object containing quotes, URLs, and other data through a POST request in Javascript

I have been researching how to convert JavaScript to JSON and properly escape characters, but I am not having much luck. I need to pass a large JavaScript object in a POST call using Postman, following this structure: { "key":"/url/url/es", "value":"{myDa ...

OpenLayers had trouble handling the mouse event in Ionic

I am attempting to handle a double mouse click event on OpenStreetMaps by utilizing the code below: const map = new OpenLayers.Map("basicMap"); const mapnik = new OpenLayers.Layer.OSM(); const fromProjection = new OpenLayers.Projection("EPSG:4326"); // ...

Switch your attention to the following input text using AngularJS

In my controller, I have an object variable called `myObject` with 3 input text fields in the user interface. I am looking for a way to automatically shift the focus to the next input field once the current one reaches its maximum length. var myObject = ...

How to determine the frequency of a specific word in a sentence using Angular 5

I need help finding a solution to count how many times a word appears in sentences. Input: k = 2 keywords = ["anacell", "cetracular", "betacellular"] reviews = [ "Anacell provides the best services in the city", "betacellular has awesome services", ...

Need to ensure that an AJAX form doesn't resubmit without the need for a page

Encountering a peculiar mystery issue here... I have created a button on a webpage that triggers a form submission. The form is enclosed within a DIV, which dynamically updates to display the modified data. (this is embedded in a smarty template) form: ...

Is there a way to create a curve that stays below the text and does not intersect with it?

I am attempting to center a text on a quadratic curve or line, as shown in the image below: https://i.stack.imgur.com/XH6Fw.png My current approach using ctx.fillText results in the text overlapping the curve. https://i.stack.imgur.com/ddwue.png Is ther ...

Analyzing the object for interface compatibility

When I receive a query string in one of my REST endpoints using koa-router, each value of the query string object parameter is always a string: { count: "120", result: "true", text: "ok" } Within my codebase, I have an Interface that represents the ...

jQuery click event handlers may become unresponsive following the loading of an HTML page using the load() method

I am facing an issue where the click event handlers associated with links in HTML pages loaded dynamically using jQuery are not working. When a link is clicked, it loads another HTML file but the event handlers seem to be lost in the process. Below is an e ...

Issue with RouterLink not recognizing QueryParams

I have encountered an issue where dynamically generated URLs with queryParams inside [routerLink] are breaking routes. For example: this.url = '/question/ask?details=1' <a [routerLink]="url"> {{ data.name }}</a> Upon mouseover, the ...

The process of efficiently uploading a batch of images to Firebase storage while also obtaining all the respective

I have been using firebase storage to upload images and save their respective URLs in the firebase database. However, I recently encountered an issue with my code. In firebase v8, everything was working fine, but after updating to version 9, the following ...

How to execute a function in a child component that is declared in the parent component using Angular

Is anyone able to help me with an issue I am facing in my Angular project? I have two components, 'app' and 'child'. Within the child component, I have a button that calls a function defined in the app component. However, this setup is ...

Showing only the objects that are marked as true in the component (React)

I have implemented two key React components. One of them is VideoGameList.js, it serves as an export of an array containing multiple objects. const VideoGameList = [ { id: 1, title: "Fire Emblem Engage", src: vg01, releaseDate: ...

Is there a way to implement jQuery.closest() using DOM manipulation or pure JavaScript?

Here is the HTML I am attempting to target. Given this HTML structure: <table class="non-unique-identifier table"> <tr><td><div id="unique-identifier"></div></td></tr> </table> I am trying to select #unique ...

Adjust the colors of two elements by clicking a button's onclick event

As stated in the title, I have a button in the books component. When this button is clicked, the color of a div within the books component and another div in the navbar component should change. - Below is the code for the books component : export class Bo ...

Stop the submission of a form using jQuery based on its unique identifier

When using the jQuery Ajax function to verify if a user email exists in the database during a jQuery change event, there are two possible outcomes in the Ajax response. If the user email does exist, an error message is displayed. In this scenario, I aim ...

Caution: When using Array.prototype.reduce(), make sure the arrow function returns a value

const filteredParams = [...appliedFilters].reduce((prev, curr) => { if (curr.key !== "multi") return { ...prev, ...curr.selectedValue.params }; return; }, {}); When I run this code, I encounter the following warning message in ...

Utilizing Mongoose for Deeply Nesting Arrays: A Comprehensive Guide to Populating Subdocuments

I am struggling with populating a deep level in my Schema. Despite searching and reading many pages, I have not been able to resolve the issue. Below is my Schema: var boxSchema = new mongoose.Schema({ name: { type: String, unique: tr ...