Didzis Stivriņš
Didzis Stivriņš

Reputation: 254

Blazor .NET 8 two-way binding with component in InteractiveServer rendering

What would be the correct way or even if it is possible to set two way binding with component that is using InteractiveServer rendering mode in .NET 8.

MainLayout.razor - I would like to receive bool value from the child component:

<SwitchComponent @rendermode="@RenderMode.InteractiveServer" @bind-Value1="@ThisValue" />

@ThisValue

@code {
    public bool ThisValue { get; set; }
}

And then the component would look like something like this:

<button @onclick="@UpdateHeading">Update </button>
@Value1 

@code {
    [Parameter]
    public bool Value1 { get; set; }

    [Parameter]
    public EventCallback<bool> Value1Changed { get; set; }

    private Task OnValue1Changed(ChangeEventArgs e)
    {
        return Task.CompletedTask;
    }

    private void UpdateHeading()
    {
        Value1 = !Value1;
        Value1Changed.InvokeAsync(Value1).GetAwaiter().GetResult();       
    }
}

The problem that I am facing is that I can't figure out how to bind the parent property ThisValue to component when child value Value1 change so should parent value!

Upvotes: 0

Views: 942

Answers (1)

Cfun
Cfun

Reputation: 9721

Use @bind-get and @bind-set

<SwitchComponent @rendermode="@RenderMode.InteractiveServer" @bind-Value1:get="ThisValue"
                 @bind-Value1:set="OnChange" />
@ThisValue
@code{
    public bool ThisValue { get;set;}
}

private void OnChange(bool value)
{
   ThisValue = value;
   //Update "ThisValue" here depending on your logic
}

Related question:

Two-way binding not working for custom input element

Official Docs:

ASP.NET Core Blazor data binding .

Upvotes: 0

Related Questions