Live Chat Icon For mobile
Live Chat Icon

How do you create a generic template component?

Platform: Blazor| Category : Components, Templated components

Templated components are often generically typed. To define a generic component, use the @typeparam directive to specify type parameters

Generic template component

@typeparam TItem

<table class="table">
    <thead>
<tr>@TableHeader</tr>
    </thead>
    <tbody>
        @foreach (var item in Items)
        {
            <tr>@RowTemplate(item)</tr>
        }
    </tbody>
    <tfoot>
        <tr>@TableFooter</tr>
    </tfoot>
</table>

@code {
    [Parameter]
    public RenderFragment TableHeader { get; set; }

    [Parameter]
    public RenderFragment<TItem> RowTemplate { get; set; }

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

    [Parameter]
    public IReadOnlyList<TItem> Items { get; set; }
}

When using generically typed components, the type parameter is inferred if possible.

<GenericTemplate Items="@forecasts">
    <TableHeader>
        <th>Date</th>
        <th>Temp. (C)</th>
        <th>Temp. (F)</th>
        <th>Summary</th>
    </TableHeader>
    <RowTemplate Context="forecast">
        <td>@forecast.Date.ToShortDateString()</td>
        <td>@forecast.TemperatureC</td>
        <td>@forecast.TemperatureF</td>
        <td>@forecast.Summary</td>
    </RowTemplate>
</GenericTemplate>
@code {
    private WeatherForecast[] forecasts;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
    }
}

Otherwise, the type parameter must be explicitly specified using an attribute that matches the name of the type parameter. In the following example, TItem=" WeatherForecast "specifies the type.

<GenericTemplate Items="@forecasts" TItem="WeatherForecast">
    <TableHeader>
        <th>Date</th>
        <th>Temp. (C)</th>
        <th>Temp. (F)</th>
        <th>Summary</th>
    </TableHeader>
    <RowTemplate Context="forecast">
        <td>@forecast.Date.ToShortDateString()</td>
        <td>@forecast.TemperatureC</td>
        <td>@forecast.TemperatureF</td>
        <td>@forecast.Summary</td>
    </RowTemplate>
</GenericTemplate>

@code {
    private WeatherForecast[] forecasts;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
    }
}

Reference: https://docs.microsoft.com/en-us/aspnet/core/blazor/templated-components?view=aspnetcore-3.1

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.