Jaime
Jaime

Reputation: 328

Dynamic class name for a div after an iron-ajax

I need to set the name of a class dynamically executing a function after an iron-ajax request.

In the template section of my element I have:

<div class="{{dynamicClass}}"></div>

I have defined this property like this:

Polymer({
        is: "fila-contenido"
        ,
        properties: {
            dynamicClass: {
                type: Number
            }
        }
        ...

I have an on-response function executed when iron-ajax responses:

_onResponse: function (e) {
            var nro = e.detail.response.length;

            switch(nro){
                case 2:
                    this.dynamicClass = "class2";
                    break;

                case 3:
                    this.dynamicClass = "class3";
                    break;
                ...
            }

        }

This function set the name of the class correctly.

The problem is the output is not showing the dynamic class but:

<div class="style-scope fila-contenido"></div>

How may I do this? Thanks!

Upvotes: 0

Views: 114

Answers (1)

tony19
tony19

Reputation: 138356

To bind to the native class attribute, use attribute binding (i.e., class$=). Otherwise, Polymer treats it as a property binding.

<div class$="{{dynamicClass}}">

HTMLImports.whenReady(() => {
  Polymer({
    is: 'x-foo'
  });
});
<head>
  <base href="https://polygit.org/polymer+1.7.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="polymer/polymer.html">
</head>
<body>
  <x-foo></x-foo>
  <x-foo clazz="highlight"></x-foo>

  <dom-module id="x-foo">
    <template>
      <style>
        .highlight {
          color: blue;
          background: lightgray;
        }
      </style>
      <span class$="{{clazz}}">hello world</span>
    </template>
  </dom-module>
</body>

codepen

Upvotes: 2

Related Questions