如何在 angular 中通过 router.navigate() 导航时添加活动 class
how to add active class when we are navigating through router.navigate() in angular
如果我使用 router.navigate()
导航到其他路线,如何根据路线添加活动 class
模板代码
<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 文件
import {Router , ActivatedRoute} from '@angular/router';
constructor(public router: Router, public route: ActivatedRoute,) { }
routingSelected(partnerCode) {
this.router.navigate([partnerCode] , { relativeTo: this.route });
}
作为解决方法,您可以将模板变量放在路由器出口指令上以获取对 ActivateRoute 信息的引用。然后使用 ngClass 可以动态添加 ngClass。
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;
}}
如果我使用 router.navigate()
导航到其他路线,如何根据路线添加活动 class模板代码
<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 文件
import {Router , ActivatedRoute} from '@angular/router';
constructor(public router: Router, public route: ActivatedRoute,) { }
routingSelected(partnerCode) {
this.router.navigate([partnerCode] , { relativeTo: this.route });
}
作为解决方法,您可以将模板变量放在路由器出口指令上以获取对 ActivateRoute 信息的引用。然后使用 ngClass 可以动态添加 ngClass。
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;
}}