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:
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');
});