Search code examples
c#blazorblazor-server-sideblazor-client-side

Passing multiple child components as parameter


So using the component would look like this:

<ParentListComponent Header="Test">
   <ChildListItemComponent Name="1"/>
   <ChildListItemComponent Name="2"/>
   <ChildListItemComponent Name="3"/>
   <ChildListItemComponent Name="4"/>
</ParentListComponent>

And the ParentListComponent would look something like this:

@foreach(var childComponent in listComponents){
    @childComponent
}

@code{

   [Parameter]
   Public List<ChildListItemComponent> listComponents { get; set; }
}

I know I could easily render it by passing it as ChildContent like shown below, but I'd really like to keep the list so I can easily access each item from the parent.

[Parameter]
public RenderFragment ChildContent { get; set; }

I feel like I'm just missing the syntax here, but unfortunately I can't find the info for this. If you can help I'd appreciate it.


Solution

  • You'd create a ParentComponent and a ChildComponent. The mark-up for ParentComponent would have the following

    <CascadingValue Value=this>
    @ChildContent
    </CascadingValue>
    
    @code
    {
      [Parameter]
      public RenderFragment ChildContent { get; set; }
    }
    

    Now your children will have access to the parent, like this

    [CascadingParameter]
    public ParentComponent ParentComponent { get; set; }
    

    In the OnInitialized method you can call ParentComponent.RegisterChild(this); and in IDisposable.Dispose you can call ParentComponent.UnregisterChild(this);

    Those are two methods you would add yourself on your parent class to keep a list of ChildComponent.

    There's a full walk-through on Blazor University here.