Stenciljs @Method not working
Methods are not immediately available on a component; they have to be loaded/hydrated by Stencil before you can use them.
Components have a componentOnReady
function that resolve when the component is ready to be used. So something like:
var myName = document.querySelector("my-name");
myName.componentOnReady().then(() => {
myName.setName('Bob', 'Smith');
});
Just posting another answer because this has since changed, with Stencil One.
All @Method
decorated methods are now immediately available on the component, but they are required to be async
, so that you can immediately call them (and they resolve once the component is ready). The use of componentOnReady
for this is now obsolete.
However, you should make sure that the component is already defined in the custom element registry, using the whenDefined
method of the custom element registry.
<script>
(async () => {
await customElements.whenDefined('my-name');
// the component is registered now, so its methods are immediately available
const myComp = document.querySelector('my-name');
if (myComp) {
await myComp.setName('Bob', 'Smith');
}
})();
</script>