How are events suppressed in Blazor?

Platform: Blazor| Category : Event handling, Tips and Tricks

Blazor provides support for suppressing events of the HTML DOM element in two ways

  • Suppressing default event
  • Suppressing event propagation

Suppressing default event:                                                                                                                        

The default events of the HTML DOM element can be suppressed by using the @on{Event}:preventDefault directive attribute provided in Blazor. This is useful in scenarios like suppressing the on key press event of an input text box.

<input type="text" @onkeypress:preventDefault />

You can also add your own event listener as done for event handling.

<input type="text" @onkeypress="EventHandlerMethod" @onkeypress:preventDefault />

Supressing event propagation:

HTML DOM element’s events tend to propagate some events to their parent element and then its parent element, and so on. Blazor provides support to supress the event propagation using the @on{EVENT}:stopPropagation directive attribute. This takes a Boolean variable as the input. This is visualized as follows.

<button @onclick:stopPropagation="true">Click</button>

As the stopPropagation attribute which takes the value of a Boolean variable can be bound to a property, the propagation can be stopped based on the user requirement.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.