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.