Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor Valued changed while keeping 2-way binding

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.

like image 667
Dylan Avatar asked Sep 10 '26 06:09

Dylan


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...

like image 144
enet Avatar answered Sep 11 '26 20:09

enet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!