Dynamically added paper button doesn't display correctly

I have the following html:

  <paper-button raised>Static</paper-button>
  <script>
    var button = document.createElement('paper-button');
    button.textContent = "dynamic";
    button.raised = true;
    document.body.appendChild(button);
  </script>

      

If I add the paper button statically, it looks fine, but I do the same thing dynamically, I get no animation.

Is there something special I need to do if I add the paper button dynamically?

see http://jsbin.com/rararurotu/1/edit?html,output

+3


source to share


2 answers


You need to install textContent

using the Polymer.dom api parameter.

The following code will work:



<paper-button raised>static</paper-button>
<script>
  var button = document.createElement('paper-button');
  button.raised = true;
  Polymer.dom(button).textContent = 'dynamic';
  document.body.appendChild(button);
</script>

      

see http://jsbin.com/gexifaxaqi/1/edit?html,output

+3


source


There are several ways to do this in Polymer 1.0.

Option 1 (using document.createElement

)

Update: I think @ Kasper's answer is the best approach when using Polymer.dom, because it allows us to inject textContent directly rather than through an inner class.

<!-- my-dom-element.html -->
<link href="bower_components/polymer/polymer.html" rel="import">
<link href="bower_components/paper-button/paper-button.html" rel="import">

<dom-module id="my-dom-element">
  <template>
    <div>
      <paper-button raised>button 1</paper-button>
    </div>
  </template>
  <script>
    Polymer({
      is: 'my-dom-element',
      ready: function () {
        var button = document.createElement('paper-button');
        button.raised = true;
        button.querySelector('.content').textContent = 'button 2';
        Polymer.dom(this.root).appendChild(button);
      }
    });
  </script>
</dom-module>

      

For details see Polymer.dom

.



Option 2 (idiomatic, using conditional templates)

Here we are using the native Polymer language to create a button element based on a condition (in this case, a property value).

<!-- my-conditional-dom-element.html -->
<link href="bower_components/polymer/polymer.html" rel="import">
<link href="bower_components/paper-button/paper-button.html" rel="import">

<dom-module id="my-conditional-dom-element">
  <template>
    <div>
      <template is="dom-if" if="{{success}}">
        <paper-button raised>
          Conditional Button
        </paper-button>
      </template>
    </div>
  </template>
  <script>
    Polymer({
      is: 'my-conditional-dom-element',
      properties:  {
        success: {
          type: Boolean,
          value: true
        }
      }
    });
  </script>
</dom-module>

      

See auxiliary elements for details .

My personal approach is that the Polymer DSL for creating components is pretty clean and it's good to take advantage of that whenever possible.

+2


source







All Articles