3

I would like to make Ctrl and Meta Key possible when users click on link inside an EmberJS app.

Is that possible to open the transitionToRoute into a new tab?

Charles
  • 11,367
  • 10
  • 77
  • 114

2 Answers2

3

If using Ember 2.16 or higher, you can use the RouterService#urlFor https://emberjs.com/api/ember/3.0/classes/RouterService/methods/urlFor?anchor=urlFor method with works exactly like transitionTo/transitionToRoute but returns a url instead of transitioning to it.

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';

export default Controller.extend({
  routerService: service('router'),

  actions: {
    openSomething(id) {
      let routerService = this.get('routerService');
      let url = routerService.urlFor('my-route', id);

      window.open(url);
    }
  }
});

For users below Ember 2.16, you can use a polyfill: https://github.com/rwjblue/ember-router-service-polyfill

EDIT 08/2020 class syntax

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';

export default class SomeController extends Controller {
  @service('router') routerService;

  @computed('model.id')
  get url() {
    let url = this.routerService.urlFor('my-route', this.model.id);

    return url;
  }
}

Note that for a more accessible app, the url generated should be on a getter using @tracked or @computed and passed to <a href={{this.url}} target='_blank' rel='noopenner noreferrer'>open</a>

knownasilya
  • 5,998
  • 4
  • 36
  • 59
2

Good question... If you use {{link-to}} then it will just work without any "hacks"...

But if you have to do it inside your click action then you can't use transitionToRoute.

You can probably check if ctrl/meta keys are down (see JavaScript: Check if CTRL button was pressed)

Then you will have to use window.open(routeUrl).

You can then generate the routeUrl using router#generate, see How to generate url for a route in Ember.js

PS: I haven't tried any of this just guessing but it already feels dirty and smells bad. I would recommend {{link-to}} if possible.

PPS: I would love to hear how you solved it :)

Emad
  • 4,110
  • 5
  • 30
  • 35
  • 1
    At the end I use `RouterService#urlFor`. I can't use `{{link-to}}` because the link is outside of EmberJS, this part isn't ported to EmberJS ATM. And yeah it's dirty :p – Charles Mar 08 '18 at 15:31