Mr. Snuffles
Mr. Snuffles

Reputation: 33

Dynamic CSS in ember component?

How to pass dynamic CSS property

{{test-component  height=height}}

test-component.hbs

<div class="flip-container ">
    <div class="flipper">
        <div class="front">
            RED SIDE
        </div>
        <div class="back">
            BLUE SIDE
        </div>
    </div>
</div>

Suppose I want to modify this CSS property

.flip-container, .front, .back {
    width: 10em;
    height: 20em;
}

I have seen bind-attr helper , but now it's deprecated.

Upvotes: 0

Views: 2028

Answers (2)

jelhan
jelhan

Reputation: 6338

I suppose you want to change inline css according to height property. If so there are to approaches:

  1. You could pass dynamic values to style attribute of an element in template: <div style="height: {{height}}px;"></div> You could find a working example in this ember-twiddle.
  2. You could observe changes to height in your component and change CSSOM accordingly: this.get('element').style.height = '10px';

There was some arguments which one should be preferred. Some argues that template binding is easier to read and feels more like the ember-way. On the other hand it requires a style-src: unsafe-inline Content-Security-Policy (CSP) which modifying CSSOM does not.

Of course if possible you should always use css classes.

Upvotes: 0

Ahmet Emre Kilinc
Ahmet Emre Kilinc

Reputation: 6885

You can directly pass class attribute to the component.

{{test-component  height=height myclass=myclass }}

test-component.hbs

<div class={{myclass}}>
    <div class="flipper">
        <div class="front">
            RED SIDE
        </div>
        <div class="back">
            BLUE SIDE
        </div>
    </div>
</div>

Checkout this twiddle.

Upvotes: 1

Related Questions