How to invoke one 2-way binding on set of another

MerleCorey76 0 Reputation points
2023-05-07T18:15:58.5933333+00:00

I have a blazor component with 2 parameters that are both 2-way bound.  When one changes, set from the outside, I need to change the other, invoked from within.  Using onparameterset leads to infinite looping.  What is the best practice for this?

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,450 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. VasimTamboli 4,780 Reputation points
    2023-05-07T19:24:45.77+00:00
    One approach to achieve this behavior is to use a flag to indicate whether the change is triggered internally or externally, and only update the other parameter when the change is external. Here's an example:
    
    csharp
    Copy code
    [Parameter]
    public string FirstParameter { get; set; }
    
    [Parameter]
    public string SecondParameter { get; set; }
    
    private bool isInternalChange = false;
    
    protected override void OnParametersSet()
    {
        if (!isInternalChange && FirstParameter != SecondParameter)
        {
            SecondParameter = FirstParameter;
        }
        isInternalChange = false;
    }
    
    private void HandleFirstParameterChanged(string newValue)
    {
        isInternalChange = true;
        FirstParameter = newValue;
    }
    In this example, OnParametersSet is called whenever either parameter changes. If the change is external (i.e., not triggered by the component itself), it updates the other parameter. The flag isInternalChange is used to prevent infinite loops by indicating whether the change is internal or external.
    
    The HandleFirstParameterChanged method can be used to update the FirstParameter from the outside, and it sets the isInternalChange flag to true to indicate that it is an internal change.
    
    Note that you can modify this approach to suit your specific requirements. For example, you can use separate methods for handling changes from the outside and inside, or you can use a different flag to indicate whether the change is from the outside or inside.
    
    0 comments No comments