I recently started using Blazor and find it a very promising technology.
I'm at the point of making custom nested Blazor components, but I don't seem to get it working the way I want.
The goal is to have a "Content" component which has a "ContentHeader" and a "ContentBody" property. However, the "ContentHeader" should be another custom component with a "Title" and "ActionBar" properties. The desired usage is as following:
<Content>
<ContentHeader>
<Title>
Title
</Title>
<ActionBar>
<button>Test button</button>
</ActionBar>
</ContentHeader>
<ContentBody>
Body
</ContentBody>
</Content>
"Content" component:
<CascadingValue Value="this">
<div class="content-container">
@ContentHeader(Header)
<div class="content-body">
@ContentBody
</div>
</div>
</CascadingValue>
@code {
[Parameter]
public RenderFragment<ContentHeader> ContentHeader { get; set; }
[Parameter]
public RenderFragment ContentBody { get; set; }
public ContentHeader Header { get; set; }
public async Task SetContentHeader(ContentHeader contentHeader)
{
Header = contentHeader;
await InvokeAsync(StateHasChanged);
}
}
"ContentHeader" component:
<div class="content-header">
<h3>@Title</h3>
<div class="content-header-action-bar">
@ActionBar
</div>
</div>
@code {
[CascadingParameter]
public Content Content { get; set; }
[Parameter]
public RenderFragment Title { get; set; }
[Parameter]
public RenderFragment ActionBar { get; set; }
protected override async Task OnInitializedAsync()
{
await Content.SetContentHeader(this);
await base.OnInitializedAsync();
}
}
The actual rendered output I get is this:
<div class="content-container">
<!--!-->
Title
<!--!-->
<!--!-->
<button>Test button</button>
<!--!-->
<div class="content-body">
<!--!-->
Body
</div>
</div>
It seems like the "ContentHeader" component its markup is completely ignored.
The <h3></h3> tags around the Title of the "HeaderComponent" are missing and the button isn't placed inside <div class="content-header-action-bar"></div>
I also notices that OnInitializedAsync of "ContentHeader" isn't triggered.
What am I doing wrong? Am I even using the right approach?
Many thanks in advance.
Kind Regards
