18

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jesse
  • 915
  • 1
  • 11
  • 20

4 Answers4

31

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;
    }
}
Sire
  • 4,086
  • 4
  • 39
  • 74
agua from mars
  • 16,428
  • 4
  • 61
  • 70
12

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; }
}
Michael
  • 1,027
  • 10
  • 22
4

you cannot do bind-value and @onchange same time

4

I found a much shorter and simpler variant.

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

Any method can then be called with @onkeyup.

MarkenJaden
  • 49
  • 1
  • 5
  • The problem with this is that binding will occur during any input event. The `SeachChanged` method will only be called when the user releases a key. If, for example the user copies and pastes data into the field then the input will change triggering the binding, but the user did not release a key, so your `SearchChanged` method will ever be called. – Jesse Apr 07 '21 at 13:00
  • 2
    The simple answer in the general case is to put your logic in your property setter. In my case a year ago when I posted this, I did not have the ability to do that because this was library code, so I had no way to access the properties. Also I did not want to program this into properties everywhere, it would've defeated the purpose of the Blazor component that I created. – Jesse Apr 07 '21 at 13:03
  • yes, property setter logic seems to be the most straight-forward to me as well, every other approach i can think of introduces to much complexity. – Yan D Feb 12 '23 at 18:35