Content Projection is the concept of generic component, which allow you to design a component that defer the specification of one or more UI part to the user of that component. In other word, you can handle the common logic and defer the specific logic to the user of that component. Some examples where Content Projection useful are: a component that will make any child component/HTML tags to display right to left; A tab container component that handles all the logic about tabs without knowing the tabs, the user of the tab container component will decide how many tabs are there. In this tutorial, you will discover:
You can download the example code used in this topic on GitHub.
In Blazor Server, there are 2 types of Content Projection:
The single-slot content projection has a single projected slot with the name ChildContent
. The following image illustrates the single-slot content projection component:
RenderFragment
in the code section. For example:@code { [Parameter] public RenderFragment? ChildContent { get; set; } }
@ChildContent
as the placeholder for projecting another content. For example:<div> @ChildContent </div>
You cannot change the parameter name of ChildContent. It is a fixed name defined by Blazor Server.
To use the single-slot content projection component you just created at the previous step, you will need to define the projecting content between the component tag. In the following example, we named our single-slot content projection component as SingleSlotChild
:
<SingleSlotChild> <span>Content to project</span> </SingleSlotChild>
The result:
The multi-slot content projection as the name suggested, it has many slots for projecting the content. Furthermore, you can name your slots as you want. The following image illustrates the multi-slot content projection component:
@code { [Parameter] public RenderFragment? Slot1 { get; set; } [Parameter] public RenderFragment? Slot2 { get; set; } }
The Slot1
and Slot2
in the above example is the slot name, you will later use this slot name to define its content. You can also set the default UI for a slot with a delegate with (__builder)
. You must follow the syntax (__builder) => { }
. For example:
[Parameter] public RenderFragment? Slot3 { get; set; } = (__builder) => { <div>Default Slot 3</div> };
<div> <h3>MultipleSlotsChild</h3> <div> @Slot1 </div> <div> @Slot2 </div> <div> @Slot3 </div> </div>
To use the multi-slot content projection component, you need to define the content for each slot with its slot name. For example:
<MultipleSlotsChild> <Slot1><span>Slot 1 content</span></Slot1> <Slot2><span>Slot 2 content</span></Slot2> </MultipleSlotsChild>
The result:
You can see the slot 3 is projecting to the default UI we have set inside the component, as the component user does not define the UI for slot 3.