Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make dynamic classNames in an ember 2.0 component?

For example: Ember components allow you to add a classNames array and those classes will be added to the main div of the component. say we have this component called new-div

export default Ember.Component.extend({
    classNames: ['container']
});

then if you inspect this component when rendered you will see:

<div id="ember595" class="ember-view container">
...
<div>

this is fine but my issue is what if i want to use this component as a fluid container sometimes and sometimes I might want to make it a jumbotron etc.

Is there a way to do this in the html and have the component.js apply it correctly?

{{new-div extra-classes='class1,class2'}}

then in the component.js:

export default Ember.Component.extend({
    classNames: [this.get('class-names')]
});
like image 626
pfg Avatar asked Jan 26 '16 17:01

pfg


3 Answers

You can add class names simply by specifying them inside the class attribute on your component:

{{new-div class="class1 class2"}}
like image 183
dimusic Avatar answered Nov 20 '22 23:11

dimusic


If you're not adding too many classes, it's easy enough with class name bindings:

export default Ember.Component.extend({
  classNameBindings: [
    'foo:bar',
    'foo:baz',
  ],
});

And set the value of foo:

{{new-div foo=true}}

This will toggle on all the above class names.

See: https://api.emberjs.com/ember/release/classes/Component/properties/classNameBindings?anchor=classNameBindings

Of course, you could get tricky with computed properties and mapping an array. Also: I like to avoid assigning dynamic class names to components explicitly. Things become messy rather quickly.

like image 23
Rimian Avatar answered Nov 20 '22 22:11

Rimian


The @dmk'solution is the cleanest one, but if your scenario it is not working you can use classNameBindings:

export default Ember.Component.extend({
  classNameBindings: ['getClassNames'],
  getClassNames: Ember.computed('extra-classes', function(){
    return this.get('extra-classes').replace(',', ' ');
  })
})
like image 14
fguillen Avatar answered Nov 20 '22 22:11

fguillen