Blazor (Razor Components) Refresh Child Component from Parent Component
Solution 1
You can try this
Child
Create a public refresh method that you can call from parent
<div class="modal">
<h3>@Title</h3>
@BodyTemplate
</div>
@code
{
[Parameter] string Title { get; set; }
[Parameter] RenderFragment BodyTemplate { get; set; }
public void RefreshMe()
{
StateHasChanged();
}
}
Parent
Call child refresh method
<MyModal Title="Super Cool Modal"
@ref="ChildComponent">
<BodyTemplate>
@MyObject.Name
</BodyTemplate>
</MyModal>
@code
{
public MyObject MyObject { get; set; } = new MyObject();
protected UploadDownloadComponent ChildComponent;
//Call this method to update the child
private void Change(TreeEventArgs args)
{
ChildComponent.RefreshMe();
}
}
Solution 2
Since <MyModal>
has a RenderFragment
parameter it's enough to call StateHasChanged()
on the parent component, it will recalculate and render all child components with parameters from the parent.
Solution 3
You can do "OnParametersSetAsync()
" on child component:
Parent component:
<childCompoment param="@paramParent" />
Child component:
[Parameter]
public string param{get;set;}
protected override async Task OnInitializedAsync(){await Refresh();}
async Task Refresh(){}
aherrick
http://twitter.com/andrew_herrick http://andrewherrick.com Run, code, slick.
Updated on June 11, 2022Comments
-
aherrick almost 2 years
I have a simple child Blazor component (MyModal) like so:
<div class="modal"> <h3>@Title</h3> @BodyTemplate </div> @code { [Parameter] string Title { get; set; } [Parameter] RenderFragment BodyTemplate { get; set; } }
In my Parent component I'm calling it like so:
<MyModal Title="Super Cool Modal"> <BodyTemplate> @MyObject.Name </BodyTemplate> </MyModal> public MyObject MyObject { get; set; } = new MyObject();
Later on after the page has initially rendered I update
MyObject
but the Child component itself referencing@MyObject.Name
never updates.Seems I have to force refresh on the child object after I've updated the Object (
StateHasChanged
) but not sure how to do this with this example. -
JamesHoux about 2 yearsWorth noting if you derive your own MyComponentBase from ComponentBase, you could add the RefreshMe() method to MyComponentBase. Then you can inherit any of your custom components from MyComponentBase and you'll get the ability to invoke RefreshMe(). Its DRY -- arguably better than adding RefreshMe() to every single component that needs it.