Generics make a Blazor template component data-aware. A type parameter identifies the row type, allowing one component to render different data models and add shared behavior. section 34.3.2
Implement a generic template component by:
- Declaring the parameter with @typeparam RowType. section 34.3.2
- Accepting data through IEnumerable<RowType> RowData. section 34.3.2
- Accepting row markup through RenderFragment<RowType> RowTemplate. section 34.3.2
- Iterating over RowData and invoking RowTemplate(item) for each row. section 34.3.2
Reuse the table for people
Use <TableTemplate RowType="Person" RowData="People"> with a header and a RowTemplate that displays each person's identifier, name, department, and location. The same component can then render departments by changing RowType, data, and row markup. section 34.3.2
Listing 34.19 Adding a type parameter in the Blazor/TableTemplate.razor file
@typeparam RowType
<table class="table table-sm table-bordered table-striped">
@if (Header != null) {
<thead>@Header</thead>
}
<tbody>
@if (RowData != null && RowTemplate != null) {
@foreach (RowType item in RowData) {
<tr>@RowTemplate(item)</tr>
}
}
</tbody>
</table>
@code {
[Parameter]
public RenderFragment? Header { get; set; }
[Parameter]
public RenderFragment<RowType>? RowTemplate { get; set; }
[Parameter]
public IEnumerable<RowType>? RowData { get; set; }
}
Inspect the complete TableTemplate.razor implementation, including its type parameter, typed data collection, and typed row template. section 34.3.2



















