Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 773
Bercovici Adrian Avatar asked Jan 24 '19 11:01

Bercovici Adrian


2 Answers

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");
      }
  }
}
like image 84
Chris Sainty Avatar answered Oct 12 '22 23:10

Chris Sainty


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;
   }
}
like image 42
enet Avatar answered Oct 13 '22 00:10

enet