Blazor component : refresh parent when model is updated from child component
Create a shared service. Subscribe to the service's RefreshRequested
event in the parent and Invoke() from the child. In the parent method call StateHasChanged();
public interface IMyService
{
event Action RefreshRequested;
void CallRequestRefresh();
}
public class MyService: IMyService
{
public event Action RefreshRequested;
public void CallRequestRefresh()
{
RefreshRequested?.Invoke();
}
}
//child component
MyService.CallRequestRefresh();
//parent component
MyService.RefreshRequested += RefreshMe;
private void RefreshMe()
{
StateHasChanged();
}
Update Parent State by calling it's StateHasChanged method
Create a Method to Update the State on Parent:
public void RefreshState(){
this.StateHasChanged();
}
Pass the Parent to the Child's by cascading Value or Parameter Example:
<CascadingValue Value="this">
<ChildComponent />
</CascadingValue>
Now on the Child's component declare the Cascading Parameter:
[CascadingParameter]
public ParentPageType _Parent { get; set; }
And Now When you want to refresh the parent just call:
_Parent.RefreshState();