Blazor channel icon Blazor · 35 published articles

Blazor WASM Event Handling And Event Arguments

In this post I will teach how to handle events inside components in your Blazor applications. All with live working demo.

Blazor WASM Event Handling And Event Arguments
On this page

What you'll learn

In this article, lets learn about Event Handling and Event Arguments in blazor wasm apps.

Note: If you have not done so already, I recommend you read the article on Blazor WASM Data Binding.

Why it matters

Event Handling in blazor components helps us to bring interactivity in our blazor applications. What should happen when a user clicks on a button or when the user hovers on element inside a component? we can run a form submit event on click of button or show an alert on click of button or animate a element inside component when the users hovers on the element, etc. We can do all these with the help of event handlers in blazor components.

The razor syntax for that is @on{DOM EVENT}="{DELEGATE}"

Razor


<h1>@currentHeading</h1>

<p>
    <label>
        New title
        <input @bind="newHeading" />
    </label>
    <button @onclick="UpdateHeading">
        Update heading
    </button>
    <button @onclick="UpdateHeadingAsync">
        Asynchronous Update heading
    </button>
</p>

<p>
    <label>
        <input type="checkbox" @onchange="CheckChanged" />
        @checkedMessage
    </label>
</p>

@code {
    private string currentHeading = "I ❤️ .NET";
    private string? newHeading;
    private string checkedMessage = "Not changed yet";

    private void UpdateHeading()
    {
        currentHeading = $"{newHeading}!!!";
    }

    private async Task UpdateHeadingAsync()
    {
        await Task.Delay(300);

        currentHeading = $"{newHeading}!!!";
    }

    private void CheckChanged()
    {
        checkedMessage = $"Last changed at {DateTime.Now}";
    }
}
        
Live demo: Event Handling — interactive controls are available when the page loads.

Implementation

Event arguments

For events that support an event argument type, specifying an event parameter in the event method definition is only necessary if the event type is used in the method. In the following example, MouseEventArgs is used in the ReportPointerLocation method to set message text that reports the mouse coordinates when the user selects a button in the UI.

Razor

@for (var i = 0; i < 4; i++)
{
    <p>
        <button @onclick="ReportPointerLocation">
            Where's my mouse pointer for this button?
        </button>
    </p>
}

<p>@mousePointerMessage</p>

@code {
    private string? mousePointerMessage;

    private void ReportPointerLocation(MouseEventArgs e)
    {
        mousePointerMessage = $"Mouse coordinates: {e.ScreenX}:{e.ScreenY}";
    }
}
        
Live demo: Event Arguments — interactive controls are available when the page loads.

Here are the list of supported event arguments:

Event Class Document Object Model (DOM) events and notes
Clipboard ClipboardEventArgs oncut, oncopy, onpaste
Drag DragEventArgs ondrag, ondragstart, ondragenter, ondragleave, ondragover, ondrop, ondragend

DataTransfer and DataTransferItem hold dragged item data.

Implement drag and drop in Blazor apps using JS interop with HTML Drag and Drop API
Error ErrorEventArgs onerror
Event EventArgs General
onactivate, onbeforeactivate, onbeforedeactivate, ondeactivate, onfullscreenchange, onfullscreenerror, onloadeddata, onloadedmetadata, onpointerlockchange, onpointerlockerror, onreadystatechange, onscroll

Clipboard
onbeforecut, onbeforecopy, onbeforepaste

Input
oninvalid, onreset, onselect, onselectionchange, onselectstart, onsubmit

Media
oncanplay, oncanplaythrough, oncuechange, ondurationchange, onemptied, onended, onpause, onplay, onplaying, onratechange, onseeked, onseeking, onstalled, onstop, onsuspend, ontimeupdate, ontoggle, onvolumechange, onwaiting

EventHandlers holds attributes to configure the mappings between event names and event argument types.
Focus FocusEventArgs onfocus, onblur, onfocusin, onfocusout

Doesn't include support for relatedTarget.
Input ChangeEventArgs onchange, oninput
Keyboard KeyboardEventArgs onkeydown, onkeypress, onkeyup
Mouse MouseEventArgs onclick, oncontextmenu, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout
Mouse pointer PointerEventArgs onpointerdown, onpointerup, onpointercancel, onpointermove, onpointerover, onpointerout, onpointerenter, onpointerleave, ongotpointercapture, onlostpointercapture
Mouse wheel WheelEventArgs onwheel, onmousewheel
Progress ProgressEventArgs onabort, onload, onloadend, onloadstart, onprogress, ontimeout
Touch TouchEventArgs ontouchstart, ontouchend, ontouchmove, ontouchenter, ontouchleave, ontouchcancel

TouchPoint represents a single contact point on a touch-sensitive device.

Summary

In this article, we learned about what is event handling in blazor components and experienced a live demo. In our next article let's learn about what is event callback and how to communicate between components.