Use a @typeparam as component in Blazor

Viewed 193

Is it possible to use a @typeparam as Component? More explicitly, do something like the following MyComponent.razor:

@typeparam TComponent

<TComponent />

Of course, there would also be a MyComponent.razor.cs file whose content would be:

public partial MyComponent<TComponent> : ComponentBase where TComponent : ComponentBase

so that the compiler would know that <TComponent /> is meaningful.

I cannot find any documentation about this in Microsoft docs.

When I try it seems to compile, but display the following warning:

warning RZ10012: Found markup element with unexpected name 'TComponent'. If this is intended to be a component, add a @using directive for its namespace

However it is only a warning and not an error. It does't show anything in the browser though.

I am using ASP.NET 5.

Thanks

1 Answers

Not quite sure what you are trying to do but you can write what I believe you are trying to achieve as a component class like this:

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;

namespace BlazorTest.Pages
{
    public class ComponentRenderer<TComponent> : ComponentBase where TComponent : IComponent
    {
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            builder.OpenComponent<TComponent>(1);
            builder.CloseComponent();
        }
    }
}

So in Index.razor you can do something like the following to render a component of type FetchData:

....
<ComponentRenderer TComponent="FetchData"></ComponentRenderer>
....

If I'm wide of the mark post a little more information.

Related