Can I bind style on a link-to?


#1

heres my link-to:

{{#link-to "projects.glob" m.id
        style=(concat "background-color:" m.color.primary)}} ...
        {{/link-to}}

I might be crazy but shouldnt there be some way of adding arbitrary attr bindings to the underlying element of the component?


#2

You have to re-open the LinkComponent class to do this:

// app/initializers/link-to-helper-extension.js

import Ember from 'ember';

export function initialize() {
  Ember.LinkComponent.reopen({
    attributeBindings: ['data-foo']
  });
}

export default {
  name: 'link-to-helper-extend',
  initialize
};

Now, data-foo gets passed onto the <a> that it renders.


#3

You can have class in link-to, and you can style your class in app.css…


#4

Like Prab said, you can pass a class instead:

<p>
  {{link-to "index" class="yourClassHere"}}
</p>

Heres the official documentation: https://guides.emberjs.com/v2.7.0/templates/links/


#5

Yeah, I suppose reopening is the way to go in this case. For my use case, its not sufficient to just add classes. I’ve got styles that are dynamic depending on the content, i.e.: models that save a color attribute to the DB, (and this is a pretty common use case, btw. I’m not sure why there isn’t an ember best practice for styling components.)…

But then, on second thought, I’ve never really styled like this, but would it be reasonable to do something like this.set("element.styles.someCssColor", color) in one of the Component lifecycle callbacks? That sounds like a better approach than the tempting solutions I’ve come up with thus far…


#6

Yes if you need to style them dynamically do it in javascript rather than inline css on the element.