mudblazor

How to access Increment and Decrement events in MudNumericField in MudBlazor?


I am using the MudNumericField component in my MudBlazor project with a step value of 0.5M, so only values like 0.5, 1.0, 1.5, etc., are allowed. If a user manually enters a value like 1.23, an error is shown—which is expected.

However, if the user enters 1.23 and then uses the mouse up/down arrows, the new value becomes 1.73 or 0.73 (i.e., 1.23 ± 0.5), which I don’t want. I’d like to round the value to one decimal place after each increment/decrement—for example, going from 1.23 to 1.5 instead of 1.73.

I noticed that OnKeyUp and OnKeyDown work for keyboard interactions but not for mouse clicks on the spinner buttons.

Is there a way to hook into the increment/decrement events of MudNumericField so I can apply my rounding logic? I’m still new to MudBlazor.

Code

<MudNumericField
T="decimal"
@bind-Value="@Days"
Label="Days"
Variant="@Variant.Text"
Min="0.5M"
Max="100"
Step="0.5M"
Error="@(!IsDaysMultipleOfHalf)"
/>

Solution

  • You can use Value & ValueChanged properties instead of @bind-Value to handle custom logic.

    Here in the example, we round the value to the closest 0.5 step directly, so if user inputs 1.23 then it will auto round and bind the value to 1 or, if the user inputs 1.73 then it changes the value to 1.5. This also means that the Error property is not really needed.

    <MudNumericField T="decimal" Value="@Days" ValueChanged="HandleChange" Label="Days" Variant="@Variant.Text" Min="0.5M" Max="100" Step="0.5M"/>
    
    @code {
        public decimal Days {get;set;}
    
        void HandleChange(decimal newValue){
            Days = Math.Round(newValue * 2, MidpointRounding.AwayFromZero) / 2;
        }
    }
    

    Demo Snippet