Find answers for the most frequently asked questions
How do I conditionally add Blazor components’ template?
The if statement is used to display a component or fragment conditionally. If the condition evaluates to true, the component will be loaded to the view.
Whenever the properties used in the if statement changes, the condition evaluates to either true or false and adds or removes the component to the page.
How do you define a render fragment using a Razor template in Blazor?
Render fragments can be defined using Razor template syntax. The templated components can be rendered either using a Razor template with an argument or directly.
@page "/razor"@{
RenderFragment template = @<p>The time is @DateTime.Now.</p>;
RenderFragment<Employee> ItemTemplate = (item) => @<p>Employee name is @item.Name.</p>;
}@template
@ItemTemplate(emp)
@code {
Employee emp = new Employee { Name = "Test" };
public class Employee
{
public string Name;
}
}
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.
Blazor supports templated components. These are components that accept one or more UI templates as parameters and these parameters can be used for component rendering.
A templated component can be created by using one or more component parameters of type RenderFragment or RenderFragment<T>. The RenderFragment is a part of the UI that is rendered by the component. It may have parameters that are used during the rendering of the component or while the RenderFragment is invoked.
Table template component
<tableclass="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<WeatherForecast> RowTemplate { get; set; }
[Parameter]
public RenderFragment TableFooter { get; set; }
[Parameter]
public WeatherForecast[] Items { get; set; }
}
When using a templated component, the template parameters can be specified using child elements that match the names of the parameters (TableHeader and RowTemplate in the following example).
How to define context in a template component in Blazor?
A parameter can be accessed by the template component (of type RenderFragment<T>) using the context property. The context parameter is the implicit parameter; however, the parameter can be changed using the Context attribute on the templated component.
Share with