简体   繁体   English

Angular 4从子OnInit检测路线?

[英]Angular 4 Detecting route from child OnInit?

I'm building a website using the Angular 4 framework, and there's lots of different components all interacting with each other. 我正在使用Angular 4框架构建一个网站,并且有很多不同的组件彼此交互。 One component, which is visible on every page, is the navbar component. 导航栏组件是在每个页面上可见的一个组件。 Each item on the navbar represents an angular module with child components. 导航栏上的每个项目都代表一个带有子组件的角度模块。

My goal is to have the item on the navbar highlighted that corresponds to the module you're currently in. Is there a way to do some sort of OnInit in an Angular module so that when a component in that module becomes the router-outlet, the module itself can tell the navbar which item to highlight? 我的目标是在导航栏中突出显示与您当前所在的模块相对应的项目。是否可以在Angular模块中进行某种OnInit操作,以便当该模块中的组件成为路由出口时,模块本身可以告诉导航栏突出显示哪个项目? Or is there a potentially better way to do this? 还是有可能更好的方式做到这一点?

My thoughts are that I'd like to avoid every component in a module making that call in their OnInit methods, if instead I could write that same code just once in the parent module. 我的想法是,我想避免模块中的每个组件都在其OnInit方法中进行调用,否则我可以在父模块中只编写一次相同的代码。

I don't think this is the best way to do it, but I've used this method before and it works for me. 我不认为这是最好的方法,但是我以前使用过这种方法,并且对我有用。 In your navbar component, inject the router so you can detect what the current URL is. 在导航栏组件中,注入路由器,以便您可以检测到当前URL。

 constructor(private router: Router){}

Then in your navbar component HTML you can use the ngClass to have the navbar components based off the router state. 然后,在navbar组件HTML中,可以使用ngClass使navbar组件基于路由器状态。

  <a routerLink="/notifications" routerLinkActive="active"><span
                    class=" glyphicon glyphicon-time"
                    [ngClass]="{'active-route': router.url === '/notifications'}"></span></a>

And then in your CSS add the rule to change the style of active route: 然后在CSS中添加规则以更改活动路线的样式:

.active-route { color:red // or whatever}

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

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