how to call child component method from parent component in blazor?

First you need to capture a reference of your child component:

<ChildComponent @ref="child" />

Then you can use this reference to call child component methods as you do in your code.

<button onClick="@ShowModal">show modal</button>

@code{
    ChildComponent child; 

    void ShowModal(){
        child.Show();
    }
}

The namespace of your component need to be added by a using either in the page or in _Imports.razor. If your component is in the sub folder Components/ChildComponent.razor then its namespace is {YourAppNameSpace}.Components

@using MyBlazorApp.Components

read the code


Here is an article I just posted on the subject using Interfaces:

https://datajugglerblazor.blogspot.com/2020/01/how-to-use-interfaces-to-communicate.html

In this example, the Index page is an IBlazorComponentParent object.

On the Login Component, the cool part is to set the Parent property, you just set Parent=this:

enter image description here

The way it works is the setter for the Parent property on the Login component calls the Register method on the parent:

[Parameter]
public IBlazorComponentParent Parent
{
    get { return parent; }
    set 
    { 
        // set the parent
        parent = value;

        // if the value for HasParent is true
        if (HasParent)
        {
            // Register with the parent to receive messages from the parent
            Parent.Register(this);
        }
    }
}

Then on the parent component or page, the Register method stores the reference to the component:

public void Register(IBlazorComponent component)
{
    // If the component object and Children collection both exist
    if (NullHelper.Exists(component, Children))
    {
        // If this is the Login component
        if (component.Name == "Login")
        {
            // Set the Login control
            this.Login = component as Login;
        }

        // add this child
        Children.Add(component);
    }
}

At this point, the parent and the Login page can communicate with each other as they both contain a ReceiveData method where you can send messages.