Alexey
Alexey

Reputation: 1424

How to call a method of the child component in Blazor

I have Foo.razor:

@foreach (var item in items) {
  <p>@item</p>
}

@code {
  private List<string> items = new List<string>();

  public void Append(string item) => items.Add(item);
}

If I have Bar.razor:

<Foo/>

@code {
  public void SomeMethod() {
    ...
  }
}

how can I call Append("something") from SomeMethod()?

Upvotes: 0

Views: 4154

Answers (1)

KrishnaDhungana
KrishnaDhungana

Reputation: 2684

Below is the example using @ref attribute. @ref provide a way to reference a component instance. Please refer to: Blazor Components

Foo

@foreach (var item in items)
{
    <p>@item</p>
}

@code {
    private List<string> items = new List<string>();

    public void Append(string item) =>items.Add(item);

    public void Refresh()
    {
        this.StateHasChanged(); //To refresh component after we have added items
    }
}

Bar

<Foo @ref="foo"/>

<button class="btn btn-primary" @onclick="SomeMethod">Add items</button>

@code {

    Foo foo;

    public void SomeMethod()
    {
        foo.Append("item1");
        foo.Refresh();
    }

}

Note:

The component variable is only populated after the component is rendered and its output includes the component's element. Until that point, there's nothing to reference. To manipulate components references after the component has finished rendering, use the OnAfterRenderAsync or OnAfterRender methods.

Upvotes: 5

Related Questions