Polymer - Custom element set a CSS class in ready callback?

638 views Asked by At

I'm trying to learn how to use Polymer and web-components and I've got this problem and I can't find any solutions.

I'm developing my own web component but I don't know to dynamically set a specific class.

Here is the way I call my component

<custom-toogle label="my label" class="blue" checked></custom-toogle>

Here is my web component

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/paper-toggle-button/paper-toggle-button.html">

<dom-module id="custom-toogle">

<style>
    label {
        display: block;
        font-weight: bold;
        color: #333;
    }

    paper-toggle-button.blue {
        --paper-toggle-button-checked-bar-color: #B3E5FC;
        --paper-toggle-button-checked-button-color: #0288D1;
        --paper-toggle-button-unchecked-bar-color: #B6B6B6;
        --paper-toggle-button-unchecked-button-color: #727272;
    }
</style>

<template>
    <label>{{label}}</label>
    <paper-toggle-button id="toggleButton"></paper-toggle-button>
</template>

<script>
Polymer({
    is: "custom-toogle",
    properties: {
        label: {
            type: String,
            value: null
        },
        checked: {
            type: Boolean,
            value: false
        },
        class: {
            type: String,
            value: 'blue'
        }
    },
    ready: function(){
        var e = document.getElementById("toggleButton");

        if(this.checked) {
            e.checked = true;
        }

        e.className += e.className + " " + this.class;

    }
});
}
</script>
</dom-module>

When I do this, the blue class is not applied but if I do a console.log(e.classList) the "blue" class IS in the list.

I've also tried to do this in my element

<paper-toggle-button id="toggleButton" class="{{class}}"></paper-toggle-button>

It doesn't work.

How can I set the class dynamically ?

Thank you !

2

There are 2 answers

1
anthony On

To get the id of an element within a Polymer element use this.$.elementId. Try this:

var e = this.$.toggleButton;
0
maxday On

To change the class, you need to use class$ instead of class

<paper-toggle-button id="toggleButton" class$="{{class}}"></paper-toggle-button>

I found this in the doc here : https://www.polymer-project.org/1.0/docs/devguide/data-binding.html