Blazor generic component

To create generic Blazor components, you can use the @typeparam directive.

In the example below, I first use a component that doesn’t have a code-behind file. Then I show what you need to do when you have a code-behind file. The main “trick” is to use a partial class.

In the example, we have a component that show the value of a parameter, and it’s type. We use it twice in the Index page to show a String and a DateTime value. (It’s the same example with and without code-behind).

Without code-behind

@page "/"

<ShowValue TheValue="@StringValue"></ShowValue>
<ShowValue TheValue="@DateTimeValue"></ShowValue>

@code
{
    protected string StringValue = "My String value";
    protected DateTime DateTimeValue = DateTime.Now;
}
@typeparam TValue

<h2>Show Value: @TheValue.ToString() @TypeDescr</h2>

@code
{
    [Parameter]
    public TValue TheValue { get; set; }

    protected string TypeDescr;

    protected override Task OnInitializedAsync()
    {
        TypeDescr = $"(type is {typeof(TValue).Name})";
        return Task.CompletedTask;
    }
}

This is what it looks like:

With code-behind

Notice that the code-behind file is a partial class, and that we therefore don’t @inherits from a base class. Index.razor is unchanged from above.

@page "/"

<ShowValue TheValue="@StringValue"></ShowValue>
<ShowValue TheValue="@DateTimeValue"></ShowValue>

@code
{
    protected string StringValue = "My String value";
    protected DateTime DateTimeValue = DateTime.Now;
}
@typeparam TValue

<h2>Show Value: @TheValue.ToString() @TypeDescr</h2>
using Microsoft.AspNetCore.Components;
using System.Threading.Tasks;

namespace TestGenericComponent.Components
{
    public partial class ShowValue<TValue> : ComponentBase
    {
        [Parameter]
        public TValue TheValue { get; set; }

        protected string TypeDescr;

        protected override Task OnInitializedAsync()
        {
            TypeDescr = $"(type is {typeof(TValue).Name})";
            return Task.CompletedTask;
        }
    }
}