Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 932
Gerrit Avatar asked Mar 15 '26 00:03

Gerrit


1 Answers

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.

like image 107
Peter Morris Avatar answered Mar 17 '26 13:03

Peter Morris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!