How to conditionally apply css classes in ember.js?

Member

by domenico , in category: Javascript , 4 months ago

How to conditionally apply css classes in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 2 months ago

@domenico 

In Ember.js, you can conditionally apply CSS classes by using the classNames property in your component or element template.


First, define an array of CSS class names in the classNames property of your component or element. For example:

1
2
3
export default Component.extend({
  classNames: ['my-component', 'my-class']
});


Then, you can conditionally add or remove CSS classes based on a property in your component or template using the classNameBindings property. For example:

1
2
3
4
export default Component.extend({
  isSpecial: true,
  classNameBindings: ['isSpecial:special-class:not-special-class']
});


In this example, the special-class will be applied when isSpecial is true, otherwise, the not-special-class will be applied.


You can also use a computed property to dynamically compute the CSS classes based on some logic. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
export default Component.extend({
  isBlue: true,
  isBold: false,
  classNameBindings: ['computedCssClasses'],

  computedCssClasses: computed('isBlue', 'isBold', function() {
    let classes = [];

    if (this.get('isBlue')) {
      classes.push('blue');
    }

    if (this.get('isBold')) {
      classes.push('bold');
    }

    return classes.join(' ');
  })
});


In this example, the blue class will be applied if isBlue is true and the bold class will be applied if isBold is true.


By using classNames, classNameBindings, and computed properties, you can conditionally apply CSS classes in Ember.js based on the state of your components or elements.