arkord
arkord

Reputation: 291

Blazor: Show content of parent component in the child component

I'm struggling with the component inheritance in Blazor. I want to create a base component MyComponentBase.razor which contains the base layout. The MyComponent.razor inherits from the MyComponentBase.razor component and contains the content.

My problem is that the page in the Blazor app shows only the content of the MyComponent.razor component but not the combined content. I couldn't find any example that explains how to do that. Can anyone help?

MyComponentBase.razor

@inherits ComponentBase

<div>
    <p>My Title</p>
    <p>My SubTitle</p>
    @ChildContent
</div>

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

MyComponent.razor

@inherits MyComponentBase

<p>My Content</p>

MyPage.razor

@page "/page"

<MyComponent/>

Expected result

<div>
    <p>My Title</p>
    <p>My SubTitle</p>    
    <p>My Content</p>
</div>

Actual result

<p>My Content</p>

Upvotes: 2

Views: 1858

Answers (1)

thalacker
thalacker

Reputation: 2837

When you inherit, you override the RenderTree. Thats why MyComponent only shows its text.

Also you do not need to inherit ComponentBase in a .razor file. You have two (good) options. Layouts or templates.

Layout(aka MyComponentBase)

@inherits LayoutComponentBase

<div>
    <p>My Title</p>
    <p>My SubTitle</p>
    @Body
</div>

Then just use it like follows:
MyComponent

@layout MyComponentBaseLayout

<p>My Content</p>

The template method you almost have.
You would just change MyComponent to

<MyComponentBase>
    <p>My Content</p>
</MyComponentBase>

Upvotes: 2

Related Questions