Using updateStyles in Polymer 2.0 only works with webcomponents-lite

676 views Asked by At

When using webcomponents-lite this.updateStyles works as expected. But on Browsers where it's not needed I do not want to load it.

Should this.updateStyles work without webcomponents-lite?

Example of non working version: http://codepen.io/daKmoR/pen/dNPdya

class XFoo extends Polymer.Element {
    static get is() { return 'x-foo'; }

    static get config() {
        return {
            properties: {
                width: {
                    type: String,
                    reflectToAttribute: true,
                    observer: '_onWidthChange'
                }
            }
        };
    }

    constructor() {
        super();
    }

    _onWidthChange(newValue, oldValue) {
        console.log('setting width');
        this.updateStyles({'--width': newValue});
    }

}
customElements.define(XFoo.is, XFoo);

Example of workaround with own updateStyles: http://codepen.io/daKmoR/pen/ggbeaR

class XFoo extends Polymer.Element {
    static get is() { return 'x-foo'; }

    static get config() {
        return {
            properties: {
                width: {
                    type: String,
                    reflectToAttribute: true,
                    observer: '_onWidthChange'
                }
            }
        };
    }

    constructor() {
        super();
    }

    _onWidthChange(newValue, oldValue) {
        console.log('setting width');
        this.updateStyles({'--width': newValue});
    }

    updateStyles(obj) {
        if (obj === undefined) {
            return;
        }
        var str = '';
        for (var p in obj) {
            if (obj.hasOwnProperty(p)) {
                str += p + ': ' + obj[p] + ';';
            }
        }
        this.style = str;
    }    

}
customElements.define(XFoo.is, XFoo);

is there a "better" way?

1

There are 1 answers

0
daKmoR On BEST ANSWER

As I needed support for inline style with CSS Custom Properties even for IE11, IE Edge I created my own Behavior for it.

In short:

  • write you inline styles to both style and data-styles (as style will delete all unknown properties in IE11, IE Edge)
  • read data-styles and use ShadyCSS.updateStyles

You can check it out here https://www.webcomponents.org/element/daKmoR/grain-update-inline-style-behavior