Blazor Valued changed while keeping 2-way binding

Viewed 524

Is there anyway to keep 2-way binding, as well as have a method called on @onchange?

Something like this.

<input class="form-control" placeholder="My Number" @bind="Record.Number"  @onchange="(()=> MyMethod())">

I'd like it to bind , but on change call some other method that isn't going to be setting the Record.Number value from the change events.

@onkeyup works, but I'd like to make sure the value actually changes.

1 Answers

This line:

<input class="form-control" placeholder="My Number" @bind="Record.Number"  
   @onchange="(()=> MyMethod())">

Can be expressed another way:

<input class="form-control" placeholder="My Number" value="@record.Number" 
            @onchange="@((args) => { record.Number = args.Value.ToString(); 
            MyMethod();})"/>

This creates a two-way binding where the input value is updated in the bound field (record.Number) as the 'change' event is triggered (this always occurs when you tab out of the control). Additionally, a call is made to the MyMethod method(used here to demonstrate that the value has been changed, and the timing (tabbing out of the control).

Here's a working example:

<input class="form-control" placeholder="My Number" value="@record.Number" 
            @onchange="@((args) => { record.Number = args.Value.ToString(); MyMethod();})">
<p>@output</p>

@code {

    private static string output;
 private void MyMethod()
    {
        output = record.Number;
    }
    Record record = new Record();

    public class Record
    {
        public string Number { get; set; }
    }
}

Hope this helps...

Related