establishing a CSS class for the containing element of an active route link in Angular version 2 or later

I have a bootstrap 4 navbar that includes a dropdown menu with routes. I am able to show the active route based on 'routerLinkActive', but I also want to style the 'dropdown-toggle' or 'nav-item' as active when one of its child elements is the active route.

How can I achieve this?

Below is a refined snippet of the code for readability:

<li *ngFor="let menuItem of MenuItems; index as i" [id]="i" class="nav-item dropdown" ngbDropdown>

  <a class="nav-link dropdown-toggle" ngbDropdownToggle>
    {{menuItem.title}}
  </a>

  <!-- dropdown menu -->
  <div *ngIf="menuItem.submenu.length > 0" class="dropdown-menu" ngbDropdownMenu aria-labelledby="i">
    <div *ngFor="let menuSubItem of menuItem.submenu">
        <a  [routerLink]="menuSubItem.path"
            [routerLinkActive]="['active-sub']" <== ** this part works and sets the class, now i need the top nav-link to be active too
            [routerLinkActiveOptions]="{exact: true}" 
            class="dropdown-item">
            {{menuSubItem.title}}
        </a>
    </div>
  </div>

</li>

Answer №1

To implement the functionality of routerLinkActive, follow this template reference example:

<li [ngClass]="{'current-link': rlRef.isActive}">
  <a [routerLink]="['/specific-page']" routerLinkActive="active" #rlRef="routerLinkActive">Custom Link</a>
<li>

Answer №2

After exploring various options, I devised an unconventional solution that bears resemblance to a previous approach. The technique involves exporting routerLinkActive as a template variable and subsequently accessing instances of the exported variable using @ViewChildren in the component. Here is how the HTML structure would look:

<li *ngFor="let menuItem of MenuItems; index as i" [id]="i" class="nav-item dropdown" [ngClass]="active: getRLA" ngbDropdown>

  <a class="nav-link dropdown-toggle" ngbDropdownToggle>
    {{menuItem.title}}
  </a>

  <!-- dropdown menu -->
  <div *ngIf="menuItem.submenu.length > 0" class="dropdown-menu" ngbDropdownMenu aria-labelledby="i">
    <div *ngFor="let menuSubItem of menuItem.submenu">
        <a  [routerLink]="menuSubItem.path"
            [routerLinkActive]="['active-sub']"
            [routerLinkActiveOptions]="{exact: true}"
            #rla="routerLinkActive"
            class="dropdown-item">
            {{menuSubItem.title}}
        </a>
    </div>
  </div>

</li>

In the component code, you can access the template variable and scan for any active RouterLinkActive objects as demonstrated below:

@ViewChildren('rla') routerLinkActiveReferences: QueryList<RouterLinkActive>;

get getRLA() {
    return !!this.routerLinkActiveReferences.find(rla => rla.isActive === true);
}

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

Can you demonstrate how to assign a CSS class to a datalist?

I have run into an issue where I can't seem to control the styling of the items on my datalist. The external styling does not provide any vertical spacing between each item. Is there a way to add this spacing? <div id="cssmenu"> <ul> ...

Encountering CORS Error When Attempting Server Call in Angular and Spring MVC

Upon attempting to log in through my Angular login page, I encountered the following error message stating 'Invalid CORS request'. Request URL:http://127.0.0.1:8088/myproduct/login Request Method:OPTIONS Status Code:403 Forbidden Remote Address: ...

Issue with Firebase Geopoints

While working on my Ionic, Angular, and Firebase app, I encountered an issue with storing data in Firestore using Geopoint. The syntax I used is: new GeoPoint(lat, lng); The problem arises when saving the data. In some documents, the saved data appears as ...

Footer not disappearing

Need assistance! My footer isn't showing up properly at the bottom even after applying clear:both. Can someone help please? If anyone can provide guidance, it would be greatly appreciated. Thanks for all your help in resolving the issue. ...

What is the best way to make an element disappear 5 seconds after the mouse has stopped hovering

#section1 { display: block; } #section2 { display: none; } #container:hover > #section2 { display: block; } <div id="container"> <div id="section1">Section1</div> <div id="section2">Section2</div> </div> ...

What is causing these headers for the children not to center properly?

I am trying to centrally align both vertically and horizontally the <div> element, with its child elements <h1> and <h2> being horizontally centered in relation to the parent <div>. To achieve this, I have created a specific class f ...

Is there a way to define the width of an element within the display:flex property in CSS?

Could you please review the following: https://codepen.io/sir-j/pen/dyRVrPb I am encountering an issue where setting the input [type=range] to 500px doesn't seem to make a difference from 100px, 500px, or 800px. This leads me to believe that display ...

Selecting multiple dates in Angular Material 7 is a breeze

Trying to figure out how to select multiple dates in the date picker using Angular Material. The official documentation for DatePicker Examples does not currently include this specific scenario. DatePicker Examples How can I enable the selection of multi ...

excess white space appears in the mobile version

I recently completed a website using both materializecss and bootstrap platforms. While I know this may not be the best practice, it worked for my needs. However, I am facing an issue with the mobile view. When I reduce the viewport size, a margin appear ...

Issue with Hover Effect for Input Type in Submit Form in HTML and CSS

In the following HTML code, a form is displayed inside a card HTML. The form appears after an onlick function which functions correctly. However, the submit button in the form below does not display a hover effect. <!-- Update details form here --> ...

Tips for resizing images to fit within a TD cell in an HTML table

Currently, I have an issue with the image display within a TD element. Despite setting a specific width for the TD, the image appears to be wider than intended. Could you offer a solution to this problem? ...

Tips for iterating through an observable using the .subscribe method

I am currently working on a function that involves looping and using .subscribe to receive an array object each time, with the intention of later pushing this data into another array. The loop itself is functional; however, there is an issue with the resul ...

The Angular compiler experiences slowness when running on two laptops with the same model

My coworker and I are baffled by the discrepancy in compilation times. Despite having identical Dell Laptop 7030 models, SSDs, hard drives, memory specs, and task manager processes, our builds vary significantly. The computers were ordered from the corpor ...

Troubleshooting the Alignment Issue in Angular Material Expansion Panel Header

I have implemented an Angular 14 Material Expansion Panel as shown in the code snippet below... <mat-nav-list> <a mat-list-item role="listitem" class="list-item-setting" id="emailTemplatesId" matTooltipPosition=&quo ...

It is impossible for me to utilize inline SVG as a custom cursor in CSS

Below is the code I have written. I am attempting to change the cursor using an inline SVG, but it doesn't seem to be working as expected. However, when I use the same code as a background, it works perfectly: .container { width: 50vw; height: ...

What is the best way to right-align navigation using bootstrap?

We are struggling to align our navigation items to the right side of our page. Despite using a container class and align-items-end, we have not been successful in achieving this. We must confess that this section is somewhat hastily put together, and we do ...

Utilizing TinyMCE with Angular 2: Customizing Editor Content with @Input Parameters

I am new to using Tinymce and I am unsure about where exactly I should place the setContent(this.content) method. The current setup I have is giving me an error: TypeError: null is not an object (evaluating 'body.nodeName') --- runTask — zone. ...

The jquery accordion title width does not align with the content width when an icon is included

Is there a way to adjust the widths of the heading and div elements after adding edit and delete icons to match the standard accordion style? Thanks <div id="accordion"> <h3><a href="javascript:;"> ...

Retrieve the text value from a changing dropdown menu in Selenium using Java

Need help selecting a value by text from a dynamic non-select dropdown. I've been looking into this and came across the following code snippet: WebElement element = driver.findElement(ByMapper.getBy(dropdown)); element.click(); List<WebElement> ...

Ensure that the JSON file containing translations is fully loaded prior to proceeding with the loading of the Angular application

In our Angular application, we have integrated internationalization using ng2-translate. We are utilizing the .instant(...) method for translations to simplify the process without having to subscribe to observables. One issue we are facing is that using . ...