Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically create elements in Polymer and setting attributes

Considering defining a polymer element

<dom-module id="custom-element"> 
  <template>
    <h1>I expect to be green</h1>
  </template>
  <script>
    Polymer({
      is: 'custom-element',
      properties: {
        color: {
          type: String,
          value: 'red'
        }
      },
      ready: function() {
        this.style.color = this.color;
      }
    });
  </script>
</dom-module>

I would expect that the following two would produce the same result:

  1. (in markup)

    <body>
      <custom-element color="green"></custom-element>
    </body>
    
  2. (in JS)

    var customElement = document.createElement('custom-element');
    customElement.color = 'green';
    document.body.appendChild(customElement);
    

But in fact it doesn't, as it seems that the properties are set and the polymer 'ready' function is triggered before the customElement is appended to document.body.

So basically I cannot dynamically create (in JS) custom elements and set them initial properties, different than the default properties.

How would you suggest I should do that?

Thanks!

like image 335
the-catalin Avatar asked Dec 15 '25 18:12

the-catalin


1 Answers

Set the color in attached callback instead of ready. Attached is called after the element has been appended in dom.

<base href="https://polygit.org/components/">
<script src="wecomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
<dom-module id="custom-element">
  <template>
    <h1>I expect to be green</h1>
  </template>
  <script>
    Polymer({
      is: 'custom-element',
      properties: {
        color: {
          type: String,
          value: 'red'
        }
      },
      attached: function() {
        this.style.color = this.color;
      }
    });
  </script>
</dom-module>


<html>

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <script>
    var customElement = document.createElement('custom-element');
    customElement.color = 'green';
    document.body.appendChild(customElement);
  </script>
</body>

</html>
like image 152
a1626 Avatar answered Dec 19 '25 07:12

a1626



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!