Reputation: 33
How to trigger a child component function from parent component and send data in stenciljs
From <parent-component>
, I am try run a function onClick and then send the data to <child-component>
in a function without using @Listen decorator.
Upvotes: 0
Views: 3451
Reputation: 4968
You can use the @Method()
decorator in the child for that:
@Component({ tag: 'child-component' })
export class Child {
@Method()
async foo() {
return 'bar';
}
}
@Component({ tag: 'parent-component' })
export class Parent {
@State() childRef?: HTMLChildComponentElement;
clickHandler = async () => {
const foo = await this.childRef?.foo();
}
render() {
return (
<Host onClick={this.clickHandler}>
<child-component ref={el => (this.childRef = el)} />
</Host>
);
}
}
See https://stenciljs.com/docs/methods.
Also note that the reference is not set until after the child has been rendered (i. e. not yet available in componentWillLoad
).
Since you've mentioned @Listen
, you might also find it useful that you can pass functions down to children as props (kind of like callbacks).
@Component({ tag: 'child-component' })
export class Child {
@Prop() clickHandler: (e: MouseEvent) => void;
render() {
return <Host onClick={this.clickHandler} />;
}
}
@Component({ tag: 'parent-component' })
export class Parent {
render() {
return <child-component clickHandler={e => console.log(e.target.tagName)} />;
}
}
Upvotes: 2