Kristijan Mihaljinac
Kristijan Mihaljinac

Reputation: 139

Best way to get list of child components in Blazor

We need to get list of child components in OnAfterRenderAsync method of parent component but, we don't know how to do that. We try with RenderBuilder and GetFrames but this is always null. We have Splitter component with N Split Areas as child components and we need to get all areas in Parent component, in OnAfterRenderAsync method.

Upvotes: 5

Views: 8813

Answers (1)

Peter Morris
Peter Morris

Reputation: 23234

If you have a parent component of type X and you want to references to all tightly coupled children of type Y (for example, TabControl and TabPages) then you can do this.

1: In the Parent add a wrapper around your @ChildContent to add a cascading value pointing to itself.

<CascadingValue Value=@this>
  @ChildContent
</CascadingValue>

2: In your children you can consume that value via a CascadingParameter

@code
{
  [CascadingParameter]
  public YourParentComponent ParentComponent { get; set; }
}

3: Your children can then notify their parent of their existence

protected override void OnInitialized()
{
    if (ParentComponent == null)
      throw .............("Must be used within MyParentComponent");
    MyParentComponent.AddChild(this);
}

If your child components are conditionally rendered then have them implement IDisposable so they can notify the parent to remove them from its list.

There's an example on Blazor University showing how to create a TabControl - https://blazor-university.com/templating-components-with-renderfragements/creating-a-tabcontrol/

Upvotes: 16

Related Questions