Why would the onChange event of InputText not fire in Blazor?

Viewed 15919

I have the following razor markup in a blazor component:

<div class="form-group row">
    <label for="name">Contact: </label>
    <InputText id="name" @bind-Value="Contact.Name" @onchange="NameChanged"></InputText>
</div>

When I modify the contact name on the form and tab out of the control the NameChange method is never called. Is there something else that I need to do in order to get the onChange event to trigger?

4 Answers

You cannot do @bind-value and @onchange because bi-directional binding subscribe to the onchange event.

But you can do it manualy :

<div class="form-group row">
    <label for="name">Contact: </label>
    <InputText id="name" Value="@Contact.Name" ValueChanged="NameChanged" ValueExpression="() => Contact.Name" ></InputText>
</div>

@code {
    private void NameChanged(string value)
    {
        Contact.Name = value;
    }
}

Try using on input (when typing every symbol) or on blur - when navigating away from a field.

<InputText id="name" @bind-Value="Contact.Name" @oninput="NameChanged" @onblur="NameChanged"></InputText>

bind-value is using @onchange to update the component value. So you can't use them together.

From MS documentation:

Using @bind with the CurrentValue property () is essentially equivalent to the following:

<input value="@CurrentValue"
    @onchange="@((ChangeEventArgs __e) => CurrentValue = 
        __e.Value.ToString())" />

@code {
    private string CurrentValue { get; set; }
}

you cannot do bind-value and @onchange same time

I found a much shorter and simpler variant.

<input @bind="searchString" @bind:event="oninput" @onkeyup="SearchChanged" >

Any method can then be called with @onkeyup.

Related