简体   繁体   English

在父组件中的元素上设置类

[英]Set class on an element in a parent component

We have a sidebar in the root of the application. 我们在应用程序的根目录中有一个侧边栏。 The sidebar is a list, and we use uiSrefActive to have an active class on the list item after it is clicked. 边栏是一个列表,单击后,我们使用uiSrefActive在列表项上添加active类。 But when you go somewhere from that component, the original list item loses the class. 但是,当您从该组件中移出某个位置时,原始列表项将丢失该类。 What I want to do is to give the list element the active class when you navigate from the first loaded component into an other component (which would structurally be the child of the previous component hence the active signal). 我想做的是,当您从第一个加载的组件导航到另一个组件(结构上是前一个组件的子组件,因此是活动信号)时,为list元素提供active类。 We also have a breadcrumb component on the top of the page, where the first parent is always the component whose list item should be active. 在页面顶部,我们还有一个面包屑组件,其中第一个父对象始终是其列表项应处于活动状态的组件。 Is there a way to achieve this? 有没有办法做到这一点?

Keeping track of your navigation stack can be done a couple ways. 跟踪导航堆栈可以通过两种方法完成。

  1. One way would be to create a service and track your navigation there. 一种方法是创建服务并在那里跟踪您的导航。 So if you were to select an item from the sidebar, its active state would be dependent on the service, and so would the breadcrumbs. 因此,如果您要从侧边栏中选择一项,则其活动状态将取决于服务,而面包屑也将取决于服务。

  2. The other way (and better way IMO) would be to rely on Angular routing. 另一种方式(也是更好的IMO)将依赖​​于Angular路由。 This implies that your navigation is based on Angular's Router. 这意味着您的导航基于Angular的Router。

<h1>Angular Router</h1>
  <nav>
    <a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
    <a routerLink="/heroes" routerLinkActive="active">Heroes</a>
  </nav>
<router-outlet></router-outlet>

routerLinkActive will apply a class called 'active' to the a element if the given routerLink is active. routerLinkActive将采用所谓的“主动”类的一个元素,如果给定routerLink处于活动状态。

You can also get the active link programmatically from your controllers using the ActivatedRoute provider . 您还可以使用ActivatedRoute提供程序以编程方式从控制器获取活动链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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