How to refresh Child component from Parent in Blazor


Step 1: Create the child component like thiss

<h3>HelloWorld</h3>
<p>Current Datetime :@CurrentDate</p>

@code {
    public string? CurrentDate { get; set; } = System.DateTime.Now.ToString();
    public void RefreshMe()
    {
        CurrentDate= System.DateTime.Now.ToString();
        StateHasChanged();
    }

}

Step 2: Call this refresh method in parent component like this

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<HelloWorld @ref="helloWorld"></HelloWorld>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

<p role="status">Current count: @currentCount</p>

@code {
    private int currentCount = 0;
    protected HelloWorld helloWorld;

    private void IncrementCount()
    {
        currentCount++;
        helloWorld.RefreshMe();
    }
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.