Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,500 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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?
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.