How do you handle events in Blazor?

Platform: Blazor| Category: Event handling

In Blazor developers can handle any event by using the on<eventname> attribute with an HTML element. The attribute’s value is treated as an event handler.

Blazor provides a set of event argument types that map to events. Following is a list of event types and the event argument type they map to:

  • Focus events: FocusEventArgs
  • Mouse events: MouseEventArgs
  • Drag events: DragEventArgs
  • Keyboard events: KeyboardEventArgs
  • Input events: ChangeEventArgs/EventArgs
  • Clipboard events: ClipboardEventArgs/EventArgs
  • Touch events: TouchEventArgs
  • Pointer events: PointerEventArgs
  • Media events: EventArgs
  • Progress events: ProgressEventArgs

In the example, the event keypress is handled by using lambda expression the event is triggered for every keypress in the input element.

<h3>Example 2</h3>
<input type="text" @onkeypress="@(e => KeyPressed(e))" />
<p>Message: @pressedkeys</p>

@code {
string pressedkeys;
private void KeyPressed(KeyboardEventArgs args)
{
    pressedkeys = "You pressed key: " + args.Key;
}
}

Reference link: https://visualstudiomagazine.com/articles/2018/10/01/blazor-event-handling.aspx

Share with

Related FAQs

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

Please submit your question and answer.