-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
We already have a way of preventing events in Blazor, but the problem is that it is very limited. The prevention only works after the event handler is over and the component rendering cycle is finished. This way it is really hard to do any advanced handling on input, like input masking for example. The existing behavior can be seen in the next example.
Existing API
<input value="@name" type="text" @onkeydown="@onKeydown" @onkeydown:preventDefault="@isPreventKey" />
@code {
private string name { get; set; }
private bool isPreventKey { get; set; }
private void onKeydown( KeyboardEventArgs args )
{
this.isPreventKey = args.Key == "a";
}
}
I am aware that we can do the JavaScript-type event handlers, eg. <input onkeydown="do some stuff here" />
, but that way, we cannot access any code from C# without additional interop calls.
My proposal is to add the PreventDefault()
method on existing event argument classes, eg KeyboardEventArgs
, MouseEventArgs
, and others. Blazor will somehow internally keep track of the event argument state, and if .PreventDefault();
was invoked the event would be canceled.
Proposed API
<input value="@name" type="text" @onkeydown="@onKeydown" />
@code {
private string name { get; set; }
private void onKeydown( KeyboardEventArgs args )
{
if ( args.Key == "a" )
{
args.PreventDefault();
}
}
}
As far as am aware, we have a similar API to the proposed one already on the navigation. So the use case would be similar.
eg.
private ValueTask OnLocationChanging(LocationChangingContext context)
{
if (context.TargetLocation == "/counter")
{
+ context.PreventNavigation();
}
return ValueTask.CompletedTask;
}