Search code examples
c#onchangeblazor

Executing method on Parameter change


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].


Solution

  • This is the best and simpler solution to your question

    Child.razor

        @( _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;
                }
        }
     }
    

    Usage

    @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;
       }
    }