Reputation: 4673
I'm struggling to get @Method in stenciljs working - any help would be appreciated.
Here's my component code with a function called setName that I want to expose on my component:
import { Component, Prop, Method, State } from "@stencil/core";
@Component({
tag: "my-name",
shadow: true
})
export class MyComponent {
@Prop() first: string;
@Prop() last: string;
@State() dummy: string;
@Method() setName(first: string, last: string): void {
this.first = first;
this.last = last;
this.dummy = first + last;
}
render(): JSX.Element {
return (
<div>
Hello, World! I'm {this.first} {this.last}
</div>
);
}
}
Here's the html and script that references the component:
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
<title>Stencil Component Starter</title>
<script src="/build/mycomponent.js"></script>
</head>
<body>
<my-name />
<script>
var myName = document.querySelector("my-name");
myName.setName('Bob', 'Smith');
</script>
</body>
</html>
Here's a screen shot of the error I'm getting which is Uncaught TypeError: myName.setName is not a function:
Upvotes: 8
Views: 5425
Reputation: 4978
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>
Upvotes: 11
Reputation: 9
Here you should not use @Method , it is not a best practice. We should always minimize the usage of @Method. This helps us to scale the app easily.
Instead pass data through @Prop and @Watch for it.
Ok , in your case , Please add async before the method name
Upvotes: 0
Reputation: 1872
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');
});
Upvotes: 13