Blazor playground

Nova v3.37.0

Preview

Blazor

Working with Slots

Working with Slots and Dynamic Content

Introduction

Nova components are built with Stencil.js and wrapped for Blazor. Because Nova uses the light DOM rather than native shadow DOM, Stencil polyfills slot behavior by physically moving slotted elements into the correct positions within the component's rendered markup. Blazor has no awareness that this DOM manipulation has occurred, which can lead to unexpected behavior when slot content changes dynamically.

This guide shows you how to work with dynamic slot content correctly.

How Slots Work in the Light DOM

When you render children inside a Nova component's slot, Stencil relocates those DOM nodes to match where the <slot> appears in the component's template. From Blazor's perspective, those elements still exist where it originally placed them — but in the actual DOM, they've been moved.

This mismatch is harmless when the slot content is static. This requires extra attention when slot content changes dynamically — for example, when you filter a list, add or remove items, or reorder children. Blazor's render tree diffing tries to patch the real DOM, but the real DOM no longer matches what Blazor expects. This can result in:

  • Items not appearing or disappearing when they should
  • Duplicate or stale items rendering
  • Console errors or visual glitches
  • Event handlers becoming detached

A Concrete Example

Consider a dropdown where the items are filtered based on user input:

razor@* This can produce unexpected results *@

<NvFielddropdown
    Filterable="true"
    ControlledFilter="true"
    FilterTextChangedEvent="OnFilterTextChanged">
    <ContentSlot>
        <ul>
            @foreach (var item in filteredItems)
            {
                <NvFielddropdownitem
                    Label="@item.Label"
                    Value="@item.Value" />
            }
        </ul>
    </ContentSlot>
</NvFielddropdown>

@code {
    private string filter = "";

    private List<DropdownItem> items = new()
    {
        new("Berlin", "berlin"),
        new("Hamburg", "hamburg"),
        new("Munich", "munich"),
    };

    private List<DropdownItem> filteredItems => items
        .Where(i => i.Label.Contains(filter, StringComparison.OrdinalIgnoreCase))
        .ToList();

    private void OnFilterTextChanged(string? value)
    {
        filter = value ?? "";
    }

    private record DropdownItem(string Label, string Value);
}

In this example, when the user types a filter and the list of <NvFielddropdownitem> elements changes, Blazor will try to patch the DOM — but Stencil has already moved those nodes. The result is unpredictable rendering.

Keeping Slot Content in Sync

The approach is straightforward: give the parent web component a @key that changes whenever its slot content changes. When the @key changes, Blazor destroys the old component instance and creates a fresh one, which allows Stencil to correctly slot the new children from scratch.

razor@* This works correctly *@

<NvFielddropdown
    @key="dropdownKey"
    Filterable="true"
    ControlledFilter="true"
    FilterTextChangedEvent="OnFilterTextChanged">
    <ContentSlot>
        <ul>
            @foreach (var item in filteredItems)
            {
                <NvFielddropdownitem
                    Label="@item.Label"
                    Value="@item.Value" />
            }
        </ul>
    </ContentSlot>
</NvFielddropdown>

@code {
    private string filter = "";

    private List<DropdownItem> items = new()
    {
        new("Berlin", "berlin"),
        new("Hamburg", "hamburg"),
        new("Munich", "munich"),
    };

    private List<DropdownItem> filteredItems => items
        .Where(i => i.Label.Contains(filter, StringComparison.OrdinalIgnoreCase))
        .ToList();

    private string dropdownKey =>
        string.Join(",", filteredItems.Select(i => i.Value));

    private void OnFilterTextChanged(string? value)
    {
        filter = value ?? "";
    }

    private record DropdownItem(string Label, string Value);
}

The critical addition is the @key on <NvFielddropdown>:

razor@key="dropdownKey"

where dropdownKey is a computed property derived from the filtered list:

csharpprivate string dropdownKey =>
    string.Join(",", filteredItems.Select(i => i.Value));

Every time the filtered list changes, the key changes, Blazor tears down the old component and creates a new one, and Stencil slots everything correctly.

Key Generation Strategies

The key you choose should change whenever the slot content changes. Here are common approaches:

Joining item identifiers

Best when items have stable, unique IDs:

csharpprivate string dropdownKey =>
    string.Join(",", items.Select(i => i.Value));

Using the list count

Sufficient when items are only added or removed (not reordered):

csharpprivate int dropdownKey => items.Count;

Using a counter

Useful when you want explicit control over when to re-mount:

csharpprivate int revision = 0;

private void HandleItemsChanged(List<DropdownItem> newItems)
{
    items = newItems;
    revision++;
}
razor<NvFielddropdown @key="revision">
    @* ... *@
</NvFielddropdown>

Hashing or serializing

For complex cases where the content shape matters:

csharpprivate string dropdownKey =>
    System.Text.Json.JsonSerializer.Serialize(items);

Tip: Prefer the simplest key that captures meaningful changes. Overly granular keys (like full JSON serialization) cause more re-mounts than necessary, while overly coarse keys (like items.Count) may miss reorder changes.

Full Example: Filtered Dropdown

This is a complete working pattern using NvFielddropdown with dynamic filtering.

razor<NvFielddropdown
    @key="dropdownKey"
    Filterable="true"
    ControlledFilter="true"
    Value="@selectedValue"
    Label="Select a City"
    Options="@dropdownOptions"
    FilterTextChangedEvent="OnFilterTextChanged"
    ValueChanged="OnValueChanged">
    <ContentSlot>
        <ul>
            @if (!filteredItems.Any())
            {
                <NvFielddropdownitem Disabled="true">
                    No results found
                </NvFielddropdownitem>
            }
        </ul>
    </ContentSlot>
</NvFielddropdown>

@code {
    private string filter = "";
    private string selectedValue = "";

    private List<DropdownItem> items = new()
    {
        new("Berlin", "berlin"),
        new("Hamburg", "hamburg"),
        new("Munich", "munich"),
        new("Frankfurt", "frankfurt"),
        new("Cologne", "cologne"),
    };

    private List<DropdownItem> filteredItems =>
        string.IsNullOrWhiteSpace(filter)
            ? items
            : items.Where(i =>
                i.Label.Contains(filter, StringComparison.OrdinalIgnoreCase))
              .ToList();

    // Key changes whenever the filtered results change
    private string dropdownKey =>
        string.Join(",", filteredItems.Select(i => i.Value));

    private NvFielddropdownOptions[]? dropdownOptions =>
        filteredItems.Select(i => new NvFielddropdownOptions
        {
            Label = i.Label,
            Value = i.Value
        }).ToArray();

    private void OnFilterTextChanged(string? value)
    {
        filter = value ?? "";
    }

    private void OnValueChanged(string? value)
    {
        selectedValue = value ?? "";
    }

    private record DropdownItem(string Label, string Value);
}

When Is This Necessary?

You only need this pattern when slot content changes dynamically. Specifically:

Scenario@key needed?
Static list of itemsNo
Filtering / searching itemsYes
Adding or removing itemsYes
Reordering itemsYes
Changing parameters on existing items onlyNo
Toggling visibility of a slot childYes

If your component's slotted children never change after the initial render, no special handling is required.

Caveats

  • Component state resets on re-mount. Because changing the @key destroys and recreates the component, any internal state (e.g., open/closed state, scroll position, filter text) will be lost. Lift any state you need to preserve into your Blazor component's fields above the keyed component.
  • Element references are reassigned. If you hold an @ref to the component, it will point to the new instance after re-mount. This is generally fine, but be aware of it if you're caching the reference.
  • Performance. Re-mounting is more expensive than patching. For most use cases this is negligible, but avoid key patterns that change on every render if slot content hasn't actually changed.

Summary

Because Stencil's light-DOM slot polyfill moves DOM nodes in ways that Blazor cannot track, the recommended approach for dynamic slot content is:

When slot content changes dynamically, set an @key on the parent web component that reflects the current content. This forces Blazor to re-mount the component, keeping Blazor and the web component in sync.

Related Documentation