A useful tip for adding an active class during navigation with router.navigate() in Angular

How can I add an active class based on the route when navigating to another route using router.navigate()

Here is the template code:

<div class="row">
    <div class="col-lg-7">
         <div class="row" *ngFor="let item of res " (click)="selected(item)">
               {{item.name}}
            <div> 
         <div>
     </div>
    <div class="col-lg-5">
      <router-outlet></router-outlet>
    </div>
</div>

In the corresponding TypeScript file:

import {Router , ActivatedRoute} from '@angular/router';

constructor(public router: Router, public route: ActivatedRoute) { }
    
routingSelected(partnerCode) {
    this.router.navigate([partnerCode] , { relativeTo: this.route });
}

Answer №1

One way to work around this issue is by placing a template variable on the router-outlet directive in order to access ActivateRoute information. By using ngClass, you can dynamically add classes.

component.html

<div class="row">
  <div class="col-lg-7">
    <div [ngClass]="{active:routerOutletVariable.isActivated && (routerOutletVariable.activatedRoute.url | async).
    some(cb(item.partnerCode))}" class="row" *ngFor="let item of res " (click)="selected(item)">
      {{item.name}}
      <div>
        <div>
        </div>
        <div class="col-lg-5">
          <router-outlet #routerOutletVariable="outlet"></router-outlet>
     </div>
  </div>

component.ts

  cb = (partnerCode)=>{return (route)=>{
  return route.path === partnerCode;
  }}

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

Is it possible to recycle an Observable within a function?

After reading numerous articles discussing Observables, Subscriptions, and different methods of unsubscribing, I found myself facing a simple question. The code snippet below is part of a function called getDataSource(): merge(this.sort.sortChange, this.pa ...

Efficiently integrating Firebase Functions with external sub path imports beyond the project's

I encountered an issue in my firebase functions project with typescript. The problem arises when I use types from outside the project with sub path imports, causing the build files to become distorted. Instead of having main:lib/index.js, I have main:lib/ ...

Leverage async-await in conjunction with subscription

I am struggling with a tangled mess of code known as 'callback hell'. Can someone please guide me on how to make use of async-await to simplify the debugging process and tidy up this situation? this.ws.call('vm.image_path', ['Ran ...

I built a custom Angular application integrated with Firebase, and I'm looking for a way to allow every user to have their individual table for managing tasks

I am looking to enhance my code so that each user who is logged in has their own tasks table, which they can update and delete. Additionally, I need guidance on how to hide menu items tasks, add-tasks, logout for users who are not logged in, and display th ...

Executing Angular async routing functions outside of the ngZone allows for more efficient

The routing function was called within a service and I am encountering the following warning message: Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'? However, I cannot simply call this.ngZone.run(...) because I ...

Troubleshooting engine malfunction in Angular 9 caused by FormGroup usage

Here is a sample code snippet of a component: export class BaseFormComponent implements OnInit { basicFormGroup: FormGroup; constructor( protected basicProviderService: BasicProviderService, protected formBuilder: FormBuilder, protected di ...

Personalize your Angular Material experience

Dealing with two components named one.component.html and two.components.html, I encountered an issue when trying to customize the Angular material datepicker for only one component. Writing custom CSS code in one.component.css did not produce the desired ...

Changing the button color dynamically in Angular Material

Currently, I am working on creating a sidebar menu with angular material. However, I am facing an issue in changing the button color based on some component property. I have gone through the documentation available at: https://material.angular.io/componen ...

Using React.ReactNode as an argument in Storybook

This is a unique button component type that I have created import React from 'react' export type ButtonProps = { label: string; color?:'primary' | 'secondary' | 'tertiary'; size?:'mobile' | 'tabl ...

Changing the order of a list in TypeScript according to a property called 'rank'

I am currently working on a function to rearrange a list based on their rank property. Let's consider the following example: (my object also contains other properties) var array=[ {id:1,rank:2}, {id:18,rank:1}, {id:53,rank:3}, {id:3,rank:5}, {id:19,r ...

Using Angular5 to extract coordinates from the Google Maps v3 API when a map "click" event occurs

Can anyone assist me with retrieving coordinates from a click event on a map? Here is the desired result: Link Below is the code I have so far: import { Component, OnInit } from '@angular/core'; import { ViewChild } from '@angular/core&ap ...

Executing callback function within Observable.prototype.subscribe in Angular 2

Having issues with the complete callback not functioning as intended. Here's a breakdown: Take a look at this image and note the complete callback within the subscribe method. The complete function is only triggered when observerOrNext is called. If ...

NGINX, Node 8.11, and Angular 6 experiencing issues with asset routing

One issue we are facing is with getting assets to load properly in our current setup. We are using NGINX, Node 8.11, and Angular 6. In summary, I had to perform some request parsing in our Node server.js in order to ensure that files loaded correctly for ...

Passing data from child components to parent components in NextJs using Typescript

I have created a new component <ConnectWallet setConnected={(t: boolean) => console.log(t)}> <>test</> </ConnectWallet> The component is initialized as follows import { useState, useEffect } from ' ...

Tips for improving DOMContentLoaded performance with Angular2

Currently, I am in the process of converting a JQuery template to Angular 2, specifically a Dashboard-like template. This website has numerous popups, each containing multiple tabs, so I decided to separate each popup into different components to keep the ...

Dealing with errors in authorized requests in Angular 6 with the help of interceptors

Within my Angular application, I have implemented an interceptor to handle authorization headers. This interceptor also specifically handles HTTP errors related to status code 401, indicating bad credentials or a missing access token on the server side. In ...

Set the initial index position to 0 for the property type

Looking to define a type for the following scenario: categories.categories[0].category.map((c: CategoryObject) => ({ category: c.name[0]._text[0], Can we specify index 0 in the type declaration? For example: type CategoryObject = { name[0]: { _te ...

How can I ensure that a user variable stored in an Angular6 service remains defined and accessible from other components?

Currently, I am working on an Angular app and facing a challenge. After receiving a user variable from an asynchronous call to Firestore Cloud, I noticed that the variable is successfully set (verified using console.log()). However, when I navigate between ...

Transferring information from childA component through its parent component and into childB component

In my project, there is a main parent component with two child components: 1. app-search-list and 2. app-vertical-menu The data is passed from the app-search-list (childA) component to its parent component, and then from the parent to the app-vertical-men ...

Update dynamically generated CSS automatically

Is there a way to dynamically change the CSS? The problem I'm facing is that the CSS is generated by the framework itself, making it impossible for me to declare or modify it. Here's the scenario at runtime: https://i.sstatic.net/IovGr.png I a ...