This code will help you to understand how to create a generic template component.
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); } }
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Templated components are often generically typed. To define a generic component, use the @typeparam directive to specify type parameters
Generic template component
When using generically typed components, the type parameter is inferred if possible.
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.
need an explanation for this answer? contact us directly to get an explanation for this answer