10
votes

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.

3

3 Answers

3
votes

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();
   }
}
1
votes

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.

0
votes

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(){}