Change variable value on input key press on Blazor

Answer:

Quoting Data Binding docs:

<input @bind="CurrentValue" 
       @bind:event="oninput" />

Unlike onchange, which fires when the element loses focus, oninput fires when the value of the text box changes.

Using @oninput:

You can achieve it without @bind directive:

<input value="@CurrentValue"
       @oninput="(e)=> CurrentValue = e.Value.ToString()"/>

InputText & oninput

To people that are looking for oninput with InputText component the answer is full documented on InputText based on the input event doc:

Use the InputText component to create a custom component that uses the input event instead of the change event. Shared/CustomInputText.razor:

@inherits InputText

<input @attributes="AdditionalAttributes" class="@CssClass" 
    @bind="CurrentValueAsString" @bind:event="oninput" />

The CustomInputText component can be used anywhere InputText is used:

<CustomInputText @bind-Value="exampleModel.Name" />

Leave a Comment