简体   繁体   中英

how to add active class when we are navigating through router.navigate() in angular

how to adding active class based on route if I am navigating to other route using router.navigate()

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>

ts file

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

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

As a Workaround you can place template variable on router-outlet directive to get reference to ActivateRoute information. Then using ngClass you can add ngClass dynamically.

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;
  }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM