0

I have multiple select fields on my component and would like to add a custom @onchange-handler (like an onafterchange or something like that) in addition to the default @bind-behavior (value and @onchange).

This handler should only set a flag to indicate that the user can save, because this selection has changed a value of the parameter. For an input field, the @oninput can be used for this (see code below).

I don't want to overwrite the default @onchange but just add this to it. Is there a way I can add this or do I have to manually overwrite the @onchange for each select field on the component?

I tested @onselectionchange, @onselect and @onselectstart but these sadly weren't called.

// MyComponent.razor

<button disabled=@IsDisabled @onclick=DoSave>Save</button>

<input type="text" @bind=TestSample.TestInputValue @oninput=SetChanged />

@* How to call SetChanged after @onselect here? *@
<select @bind=TestSample.TestOptionValue>
    <option value="A">A</option>
    <option value="B">B</option>
</select>

@code {
    [Parameter]
    public TestSample TestSample { get; set; }

    private bool IsDisabled;

    protected override void OnInitialized()
    {
        base.OnInitialized();
        IsDisabled = true;
    }
    
    private void SetChanged()
    {
        IsDisabled = false;
    }

    private void DoSave()
    {
        // Do some Task...
    }
}
// TestSample.cs

public class TestSample
{
    public string TestOptionValue { get; set; }
    public string TestInputValue { get; set; }
}

1 Answer 1

1

You have multiple options here. One would be to wrap it into an EditContext and subscribing to the FieldChanged event or what I would suggest in your case is not to use @bind and set the value of TestSample.TestOptionValue inside the callback handler. In the next step, you set the value to the field/property. In the handler, you do the additional logic and setting the value.

<select @oninput=@HandleSelect value="@TestSample2.TestOptionValue">
    <option value="A">A</option>
    <option value="B">B</option>
</select>

@code {
   private void HandleSelect(ChangeEventArgs args)
   {
        TestSample.TestOptionValue = args.Value as String;
        SetChanged();
   }
}

Remember that @bind is to simplify "trivial" operation, where your only interest is to get a value back from an event. What @bind does is nothing else than subscribing to the event and set the value of the property/field to the ones provided in the handler.

So, if you want to do more than this operation, you can "bind" by yourself and do additional logic inside the callback.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.