How to conditionally add Blazor Component's Template?

Viewed 1483

I'm using a third party blazor component that receives a template, but I'm making a wrapper for that component that will also have a template property.

If someone use my wrapper with the template, it should pass the template, but if not, it should use the default template of the component.

What I tried is adding an if, but it doesn't work

@if (ItemTemplate != null)
    <ItemTemplate Context="Data">
            @ItemTemplate(Data)        
    </ItemTemplate>
}

It gives me an error

Unrecognized child content inside component 'TelerikDropDownList'. The component 'TelerikDropDownList' accepts child content through the following top-level items: 'ValueTemplate', 'HeaderTemplate', 'FooterTemplate', 'ItemTemplate'

But if I add it the If inside ItemTemplate

<ItemTemplate Context="Data">
    @if (ItemTemplate != null)
    {
        @ItemTemplate(Data)
    }
</ItemTemplate>

It will render nothing, because the template content is empty.

How can I add ItemTemplate conditionally or use the default value of the components ItemTemplate?

Observation: I'm using Telerik, but this question should be generic for any component with templates

1 Answers

Consider moving the check out of the component declaration. Here is an example. Let's assume you have two components: InnerComponent and WrapperComponent. Your code should look like this in the WrapperComponent:

@if(CustomTemplate == null)
{
   <InnerComponent />
}
else
{
    <InnerComponent>
        <ItemTemplate>@ItemTemplate</ItemTemplate>
    </InnerComponent>
}
Related