Dynamic Event Listeners Considerations
Consider these guidelines when using lwc:on.
- Mutating the object referenced by the variable that's passed to
lwc:onis not allowed. To modify a property on the object, pass a new object instead. Reusing the same object with modified properties throws an error. - Reassigning the variable that's passed to
lwc:onto a new object is allowed.- If a property was in the previous object but ommited in the new object, then the corresponding event listener is removed.
- If a property was not in the previous object but present in the new object, then the corresponding event listener is added.
- If a property is present in both objects, then the corresponding event listener is updated.
- We recommend that you use the
lwc:ondirective instead oflwc:spreadfor dynamically adding event listeners. - Using
lwc:onand anoneventlistener for the same event type in the HTML template throws an error. - Using both
lwc:onandlwc:spreadto specify listeners for the same event type results in both event listeners getting added to the element.
To set properties and attach event listeners based on which component is dynamically loaded, use these template directives on your component.
- Load components dynamically using
lwc:componentandlwc:is - Specify which properties to pass using
lwc:spread - Specify which event listeners to attach to the components using
lwc:on
See Also
- Attach Event Listeners Declaratively and Dynamically
- Attach Event Listeners and Pass Properties to Dynamic Components