Dynamic Event Listeners Considerations

Consider these guidelines when using lwc:on.

  • Mutating the object referenced by the variable that's passed to lwc:on is 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:on to 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:on directive instead of lwc:spread for dynamically adding event listeners.
  • Using lwc:on and an onevent listener for the same event type in the HTML template throws an error.
  • Using both lwc:on and lwc:spread to 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:component and lwc:is
  • Specify which properties to pass using lwc:spread
  • Specify which event listeners to attach to the components using lwc:on

See Also