I'm feeling stuck with this particular test case. In the ending part of the html code, I have:
<template id="test">
<test-tag class="test-id"></test-tag>
</template>
Within the script:
class TestTag extends HTMLElement {
constructor() {
super();
console.log("TestTag created");
}
get Property() : string {
return "Hello";
}
}
// inside a function:
customElements.define("test-tag", TestTag);
customElements.whenDefined("test-tag").then(() => {
console.log("test-tag defined");
var tag = document.createElement("test-tag") as TestTag;
console.log(tag.Property);
var template = document.getElementById("test") as HTMLTemplateElement;
var clone = template.content.cloneNode(true) as DocumentFragment;
var tag2 = clone.querySelector<TestTag>(".test-id");
if(tag2 == null){
console.error("tag2 is null");
} else {
//customElements.upgrade(tag2);
if(!(tag2 instanceof TestTag)){
console.error("WTF?!"); //did not expect to be here
}
console.log(tag2.Property); //tag2.Property is undefined
}
});
The first instance of tag
behaves exactly how I wanted it to. However, the second one is not cooperating: it seems like when cloning the template, it creates a generic DOM element instead of an actual instance of my TestTag
class.
In my understanding, the main purpose of custom elements is to define specific behavior and reuse it while designing complex divs using HTML markup rather than messy code involving multiple createElement
/appendChild
calls. So it appears that I might be overlooking something obvious here. Could it possibly be related to the shadow DOM mechanism or maybe customElements.upgrade()
isn't working in this scenario?
My question boils down to this: if there's a key aspect of utilizing custom elements efficiently that has slipped past me, please enlighten me on it. If not, what steps can I take to ensure that the tag2
value in the given example truly represents a TestTag
instance, and why does the current behavior occur in such a manner?