Charlie Laabs
Charlie Laabs

Reputation: 173

Dynamically append child element on load in Polymer 2.0

I'm trying to upgrade to Polymer 2.0 and I can't seem to append child elements on a parent element's load like I could in 1.X. Previously, I think I just used the ready callback, but it seems all the callbacks have changed.

Seen here in the Callback contracts have changed section.

I've tried running

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

on ready and attached, yet it seems to be executing the line before parent-element is even created. This causes an exception:

TypeError: Cannot read property 'appendChild' of null

I've also tried using

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

where container is the id of an empty <div> inside the parent element, but I get the same issue. I'm pretty new to Polymer, so if there's a better method or structure I can use to get what I need, let me know.

Upvotes: 3

Views: 780

Answers (1)

Jacob Phillips
Jacob Phillips

Reputation: 9264

From the 1.x -> 2.x upgrade guide:

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

The ready() callback is now asynchronous (microtask) due to the webcomponents v1 spec. To mitigate this, use settimeout, which is another task at the browser level and runs after microtasks. Source of next code block.

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

If you want to dig into tasks and microtasks this blog post is a great read.

Upvotes: 2

Related Questions