Access the current route name from the controller or component

I need to apply the β€œactive” class to the boot tab depending on the current route name. The route object contains a "route name", but how do I access it from a controller or component?

+6
source share
6 answers

For Ember 2, from the controller you can try:

appController: Ember.inject.controller('application'), currentRouteName: Ember.computed.reads('appController.currentRouteName') 

Then you can pass it to the component.

+2
source

Use this.controllerFor('application').get('currentRouteName');

+9
source

In an absolutely desperate case, you can search for a router or application controller (which provides the currentRouteName property) through this.container.lookup("router:main") or this.container.lookup("controller:application") from within the component.

If this were a general trend for me, I would make a CurrentRouteService and inject it into my components so that I can more easily make fun of things in my tests.

A better answer may also come up, but container.lookup () should knock down your current blocker.

+4
source

Try it.

 export default Ember.Route.extend({ routeName: null, beforeModel(transition){ //alert(JSON.stringify(transition.targetName) + 'typeof' + typeof transition.targetName); this.set('routeName', transition.targetName); }, model(){ // write your logic here to determine which one to set 'active' or pass the routeName to controller or component } 

`

+1
source

In fact, you do not need to apply the active class yourself. The link-to helper will do this for you.

Look here :

{{link-to}} will apply the CSS class name to "active" when the current application route matches the specified route. For example, if the current application route is "photoGallery.recent", use {{link-to}} :

 {{#link-to 'photoGallery.recent'}} Great Hamster Photos {{/link-to}} 

will result in

 <a href="/hamster-photos/this-week" class="active"> Great Hamster Photos </a> 
+1
source

Using the ideas from @ maharaja-santhir's answer, you might consider setting the routeName property on the target controller for use, for example, in the target template. Thus, there is no need to define logic in several places and, therefore, to reuse the code. Here is an example of how to do this:

 // app/routes/application.js export default Ember.Route.extend({ ... actions: { willTransition(transition) { let targetController = this.controllerFor(transition.targetName); set(targetController, 'currentRouteName', transition.targetName); return true; } } }); 

Defining this willTransition action in the application route allows you to distribute the current route name anywhere in the application. Note that the target controller will retain the currentRouteName property parameter even after going to another route. This requires manual cleaning if necessary, but it may be acceptable depending on your implementation and use.

0
source

Source: https://habr.com/ru/post/987094/


All Articles