Given a child and a parent component I am trying to execute a method within the child
when a parameter
has changed (from the parent).
Parent
<Child value=@IsChanged></Child>
<button onclick="Update"></button>
@functions(){
public bool IsChanged{get;set;}
public void Update()
{
this.IsChanged!=this.IsChanged;
}
Child
@(value?"True":"False")
@functions()
{
[Parameter]
protected bool value {get;set;}
public void SideEffect()
{
Console.WriteLine("has changed"); //i want this method executed when value changes from parent
}
As you can see i need to execute the method inside the Child
onchange of the parameter.The parameter is changed in the parent.
P.S
I have looked on the onchange
eventhandler but i need to execute on a [Parameter]
.
You should override the OnParametersSet
or OnParametersSetAsync
lifecycle method.
Child
@(_value ? "True" : "False")
@code()
{
private bool _value;
[Parameter] public bool Value { get; set; }
protected override void OnInitialized()
{
_value = Value;
}
protected override void OnParametersSet()
{
if (_value != Value)
{
_value = Value;
Console.WriteLine("a parameter has changed");
}
}
}
This is the best and simpler solution to your question
@( _Value ? "True" : "False")
<div>@message</div>
@code
{
[Parameter]
public bool Value { get;set; }
// [Parameter]
// public EventCallback<bool> ValueChanged { get;set; }
private bool _value;
private bool _Value
{
get => _value;
set
{
if ( _value != value)
{
_value = value;
SideEffect();
// ValueChanged.InvokeAsync(_value);
}
}
}
private string message;
public void SideEffect()
{
message = $"Parameter has changed: {_Value}"; //i want this method executed when value changes from parent
}
protected override void OnParametersSet()
{
if (_Value != Value)
{
_Value = Value;
}
}
}
@page "/"
<Child Value="IsChanged" />
<button type="button" @onclick="Update">Update</button>
<div>IsChanged: @IsChanged</div>
@code
{
private bool IsChanged { get; set; } = true;
public void Update()
{
IsChanged = !IsChanged;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With