How to create dynamic class names in ember 2.0 component?

For example: Ember components allow you to add an array of classNames, and these classes will be added to the main component div. let's say we have this component called new-div

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

then if you check this component during visualization, you will see:

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

This is normal, but my problem is that if I want to use this component as a container for liquid, sometimes, and sometimes I may want to make it jumbotron, etc.

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

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

then in component.js:

 export default Ember.Component.extend({ classNames: [this.get('class-names')] }); 
+8
source share
5 answers

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

 {{new-div class="class1 class2"}} 
+12
source share

@ dmk'solution is the cleanest, but if your script doesn't work, you can use classNameBindings :

 export default Ember.Component.extend({ classNameBindings: ['getClassNames'], getClassNames: Ember.computed('extra-classes', function(){ return this.get('extra-classes').replace(',', ' '); }) }) 
+14
source share

Alternatively, you can use something like this

 export default Ember.Component.extend({ attributeBindings: ['style'], style: function(){ return new Ember.Handlebars.SafeString('class="foo bar"'); }.property(), }); // NOT sure on this one untested export default Ember.Component.extend({ attributeBindings: ['classNames'], classNames: function(){ return 'foo bar'; }.property(), }); 
0
source share

If someone uses ember-component-css , you can try using the join-classes or local-class attribute.

 {{join-classes styles.myclass1 attributeValue}} 

attributeValue can be a value from the component controller (I mean component.js ) or the element inside the each block.

If styles.myclass1 = .class1 and attributeValue = .dummy , then the selectors will be available as .class1.dummy in styles.css .

 local-class={{(concat "myclass-" myvalue)}} 

If myvalue = 'part' , then the generated class name will include tree-to-component_myclass-part__sdfje2jbr2 (the last part is generated by id) and will be available in the stylesheet as .myclass-part .

0
source share

If you do not add too many classes, this is simple enough with class name bindings:

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

And set the value to foo:

{{new-div foo=true}}

This will switch to all the above class names.

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

Of course, you can get confused with computed properties and array mapping.

0
source share

All Articles