简体   繁体   中英

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM