Reputation: 8645
I have the following lit web component
<my-element></my-element>
Inside my-element is a button that should call the parent web component test function when clicked.
How can I do this using lit elements?
Upvotes: 3
Views: 2602
Reputation: 780
This can be done by directly setting the property on my-element
using Property Expressions.
For example, in the block of code below. my-element
has a property onPress
. The parent-el
can set the property directly by setting .onPress=${/* Function */}
.
This is a declarative alternative to the following that could be put in the parent element:
this.shadowRoot.querySelector('my-element').onPress = () => console.log('pressed');
Full example:
@customElement('parent-el')
export class ParentEl extends LitElement {
render() {
return html`<my-element
.onPress=${() => console.log('called')
}></my-element>`;
}
}
@customElement('my-element')
export class MyEl extends LitElement {
@property()
onPress = () => {};
render () {
return html`<button @click="${this.onPress}">Call passed function</button>`;
}
}
And live example: https://lit.dev/playground/#gist=5da1cb16373f7fca9c8a7cbdc5a22e4a
Upvotes: 3