Custom elements which contains other custom elements
If a custom element contains another custom element, the order of the life cycle callbacks are:
- Parent created
- Parent attached
- Child created
- Child attatched
To be able to access methods and properties on the child element from the parent element, set an attribute on the child element when it’s created, i.e. this.setAttribute('element-created', '')
and use a MutationObserver in the parent element, i.e.
var childElement = document.createElement('my-child-element');
this.appendChild(childElement);
var observer = new MutationObserver( mutations => {
mutations.forEach( mutation => {
if (mutation.target.nodeName.toLowerCase() === 'my-child-element' && mutation.attributeName === 'element-created') {
// do stuff
}
});
}).observe(childElement, { attributes: true });