Is it possible to instantiate a web component without registering it to the CustomElementRegistry
? consider a simple component:
export class MyCustomElm extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.shadowRoot!.innerHTML = `
<div>Hello world</div>
`;
}
}
// Is it really required?
customElements.define('my-custom-elm', MyCustomElm);
I am using storybook for building a library of web-component. All the examples/demos are web components. The code will always use constructor syntax, i.e. new MyCustomElm()
to initialize the component. It will never be used via plain HTML.
I tried to not register the element but it doesn't seem to work. It throws an exception if a constructor is invoked without registering a component. Since there are lots of demo components, it quickly becomes unwieldy to come up with unique names.
Alternately, is there any way to use storybook for web-components without having to set up extra web components for stories? (I tried DOM manipulations but it also spirals out of hand.)
Yes if you want to instantiate a Custom Element with new
, you'll need to define it first with customElements.define()
.
It's because your custom element derives from HTMLElement, so it must part of the Custom Elements Registry when super()
is called from the constructor()
method.
If you remove the extends HTMLElement
and super()
code parts from your class definition, you'll be able to instantiate it with new
but it will a standard Javascript object, not a custom HTML element.