Search code examples
c#asp.net-coreweb-applicationscomponentsblazor

Blazor set value inside other component


I'm building my page and I was wondering if I can make my life easier and put some simple custom Input boxes inside method and them pass reference to my values to them

<div class="col-12 row">
    <label class="col-2">@Caption</label>
    <InputNumber class="form-control col-3" @bind-Value="@Value"/>
</div>
<br />

@code {
    [Parameter]
    public string Caption { get; set; }
    
    [Parameter]
    public int Value { get; set; }
}

And then use it like

<CustomInputNumber Caption="Price" Value="@Product.Price" />

It is possible to set value like that? Or pass object as reference? Thanks for help!


Solution

  • The way I would go about this is inheriting from inputbase and basically building your own input. Chrissainty has an excellent blog post about, which I think is much clearer then me citing half of what he already explains in that post.

    https://chrissainty.com/building-custom-input-components-for-blazor-using-inputbase/

    If however you really want to wrap the already existing inputcomponent, you could do it like this:

    The component

    <div class="col-12 row">
        <label class="col-2">@Caption</label>
        <InputNumber class="form-control col-3" Value="Value" TValue="int" ValueChanged="HandleValueChanged" ValueExpression="(()=>Value)"  />
    </div>
    <br />
    
    @code{
        [Parameter]
        public string Caption { get; set; }
    
        [Parameter]
        public int Value { get; set; }
    
        [Parameter]
        public EventCallback<int> ValueChanged { get; set; }
    
        public void HandleValueChanged(int newValue)
        {
            ValueChanged.InvokeAsync(newValue);
        }
    }
    

    Usage like:

    <ExampleComponent @bind-Value="ExampleValue"/>
    

    Here you basically override the existing events that exist on a default inputfield. When the default component notices a change, you call your own valuechanged event to pass the event to it's parent.

    Though again, I think the first solution is much cleaner.