Angular - Apply style to element depending on sibling RouterLinkActive?

北城余情 提交于 2019-12-07 05:02:20

问题


I do not have only one menu bar on my app that I need to be painted when the user navigates, I have another components too that needs to be painted as well. Can I achieve this just using routerLinkActive?

menu.html

<menu>
  <a routerLink="page1" routerLinkActive="active">
      option1
  </a>
  <a routerLink="page2" routerLinkActive="active">
      option2
  </a>
</menu>

This menu works great. But what I'm asking is how can I take advantage of routerLinkActive property placed in other HTML Tag. like:

main.html

<main>
    <span class="title" routerLinkActive="active">My sub child part</span>
</main>

回答1:


You could bind the state of the routerLinkActive directive to whether or not a class is applied to an element as follows:

<a routerLink="page1" routerLinkActive="active" #rla="routerLinkActive"/>
<span [class.active-span]="rla.isActive"></span>

.active-span {
 background-color: red;
}

#rla is a template variable You can find more info about this use case of the RouterLinkActive directive in the docs




回答2:


you can apply the RouterLinkActive directive to an ancestor of a RouterLink.

<div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
  <a routerLink="/user/jim">Jim</a>
  <a routerLink="/user/bob">Bob</a>
</div>

More details here.

Hope this helps!!




回答3:


If you're main navigation item merely serves as a open/close mechanism for the submenu, but you still want to use the routerLinkActive mechanism built in to Angular, you can 'dupe' the parent item to thinking it's actually a routerLink. Like this:

<nav class="main-nav">
  <a routerLink="/someroute"
     routerLinkActive="active">somelink to a route</a>
  <a (click)="openSubMenu('some-sub-menu')"
     routerLinkActive="active"><span          
     routerLink="/parentlink"
      [hidden]="true">hidden</span>Some Sub Route</a>
</nav>
<nav class="sub-nav">
  <a *ngIf="activeSubMenu ==='some-sub-menu'"
     routerLinkActive="active"
     routerLink="/parentlink/youractualsubroute">Some Sub-route</a>
</nav>

The trick is in the 'hidden' < span > element with the parent link. This will make sure the parent link is also highlighted with the routerLinkActive property on the parent element.



来源:https://stackoverflow.com/questions/44376598/angular-apply-style-to-element-depending-on-sibling-routerlinkactive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!