Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does Blazor support passing directly components as generic arguments?

Either I am missing something or this documentation falls short: https://learn.microsoft.com/en-us/aspnet/core/blazor/components/generic-type-support?view=aspnetcore-8.0 All examples are about passing data, while I am interested in passing (directly) a component.

Say I have MyComponent and generic container MyContainer<TComponent>. Within the container .razor page I would like to write:

  @typeparam TComponent where TComponent : ComponentBase
  ...
  <h1>This is my component</h1>
  <TComponent></TComponent>

with such code I am getting error "Found markup element with unexpected name TComponent".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Remark: directly means not using DynamicComponent.

>Solution :

Since you want to directly pass a component and render it, I suggest you to add a RenderFragment parameter to your component.

FooComponent.razor:

<h1>This is my component</h1>
@ChildContent

@code {
    [Parameter, EditorRequired]
    public required RenderFragment ChildContent { get; set; }
}

You can pass a component to render to this component like this:

<FooComponent>
    <MyCustomComponent />
</FooComponent>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading