Dynamically add child on load in Polymer 2.0

I am trying to upgrade to Polymer 2.0 and I cannot add children on loading the parent like I could in 1.X. I used to think I was just using a callback ready

, but it looks like all the callbacks have changed.

Look here in the section Callback Contracts have changed section.

I tried to work

document.getElementById("parent-element").appendChild(document.createElement("child-element"));

      

on ready

and attached

, but it looks like it executes the string before it parent-element

even gets created. This throws an exception:

TypeError: Cannot read property 'appendChild' of null

      

I have also tried using

this.$.container.appendChild(document.createElement("child-element"));

      

where container

is id

empty <div>

inside the parent, but I get the same problem. I'm new to Polymer, so if there is a better method or framework I can use to get what I need, please let me know.

+3


source to share


1 answer


From the 1.x -> 2.x manual:

  • For standard DOM operations, remove the wrapper Polymer.dom ().
  • Use this.shadowRoot instead of Polymer.dom (this.root).

The callback is ready()

now asynchronous (microtask) due to webcomponents v1. To mitigate this use settimeout

, which is another browser level task and runs after microtasks. The source of the next block of code .



ready() {
  super.ready();
  setTimeout(function() {
    var distributedNodes = this.$.slot.assignedNodes({flatten: true});
    console.log(distributedNodes);
  }.bind(this), 0);
}

      

If you want to delve into tasks and microgoods this blog post is great read .

+2


source







All Articles