Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function as a property to lit element?

Tags:

lit-element

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?

like image 752
Chris Hansen Avatar asked Oct 23 '25 23:10

Chris Hansen


1 Answers

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

like image 144
YouCodeThings Avatar answered Oct 25 '25 22:10

YouCodeThings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!