Blazor child to parent two-way binding on input-text field

487 views Asked by At

I've tried to find a way to pass value from child component to parent without calling a method in parent component like

<child ValChanged="DoSomethingMethod"/>

and eventually find how to do this
child:

    <div class="form-group">
    <label>@Label</label>
    <input class="form-control" @bind="@Val" @bind:event="oninput" />
</div>

    @code{
        [Parameter]
        public string Label { get; set; }
        [Parameter]
        public EventCallback<string> ValChanged { get; set; }
        private string val;
        [Parameter]
        public string Val
        {
            get => val;
            set
            {
                if (val!=value)
                {
                    val = value;
                    ValChanged.InvokeAsync(val);
                }
            }
        }
    }

parent:

    @page "/"
<div class="row">
    <div class="col">
        <Inp Label="@Label" @bind-Val="@Result"></Inp>
    </div>
    <div class="col">
        <Res Description="@Label" Val="@Result"></Res>
    </div>
</div>



      @code{
    public string Label {get;set;}="Simple input";
    public string Result {get;set;}
}

this works and I'm happy, but when removing if(val!=value){} condition from a child component and leaving just set {val=value;ValChanged.InvokeAsync(val);} it stops working and if I change values on the input field app just freezes. So, could anyone explain the reason why? Thank you

1

There are 1 answers

2
enet On BEST ANSWER

You're having an infinite loop wherein the char, say 'a', you type into the textbox is assigned to the val variable, after which you trigger the EventCallback to update the Result property on the Index component, and then a re-rendering of the child component takes place with the @bind-Val attribute set to the value ('a') contained in the Result property. Now the child component is re-render with the same value ('a'), which is assigned to the val variable, which trigger the EventCallback to update the Result property on the Index component, ....... and so on and so forth, infinitely.

You may run your app in debug mode to see this...

This is why you should always check that the value of val is different than the value of the value variable