Angular playground

Nova v3.37.0

Preview

Angular

Working with Slots

Working with Slots and Dynamic Content

Introduction

Nova components are built with Stencil.js and wrapped for Angular. 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. Angular 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 Angular'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. Angular tries to update the DOM to reflect its view, but the real DOM no longer matches what Angular 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:

typescript// This can produce unexpected results
import { Component } from '@angular/core';

@Component({
  selector: 'app-broken-example',
  template: `
    <nv-fielddropdown
      [filterable]="true"
      [controlledFilter]="true"
      (filterTextChanged)="onFilterTextChanged($event)">
      <ul slot="content">
        @for (item of filteredItems; track item.value) {
          <nv-fielddropdownitem
            [label]="item.label"
            [value]="item.value">
          </nv-fielddropdownitem>
        }
      </ul>
    </nv-fielddropdown>
  `,
})
export class BrokenExampleComponent {
  filter = '';

  items = [
    { label: 'Berlin', value: 'berlin' },
    { label: 'Hamburg', value: 'hamburg' },
    { label: 'Munich', value: 'munich' },
  ];

  get filteredItems() {
    return this.items.filter((item) =>
      item.label.toLowerCase().includes(this.filter.toLowerCase())
    );
  }

  onFilterTextChanged(event: CustomEvent<string>) {
    this.filter = event.detail;
  }
}

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

Keeping Slot Content in Sync

Unlike React and Vue, Angular does not have a built-in key directive that you can place on any element to force its re-creation. Instead, the recommended approach is to conditionally remove and re-add the component using @if, which forces Angular to destroy the old instance and create a fresh one. This allows Stencil to correctly slot the new children from scratch.

The pattern involves briefly toggling the component out of the DOM and back in whenever slot content changes:

typescript// This works correctly
import { Component, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-working-example',
  template: `
    @if (dropdownVisible) {
      <nv-fielddropdown
        [filterable]="true"
        [controlledFilter]="true"
        (filterTextChanged)="onFilterTextChanged($event)">
        <ul slot="content">
          @for (item of filteredItems; track item.value) {
            <nv-fielddropdownitem
              [label]="item.label"
              [value]="item.value">
            </nv-fielddropdownitem>
          }
        </ul>
      </nv-fielddropdown>
    }
  `,
})
export class WorkingExampleComponent {
  filter = '';
  dropdownVisible = true;

  items = [
    { label: 'Berlin', value: 'berlin' },
    { label: 'Hamburg', value: 'hamburg' },
    { label: 'Munich', value: 'munich' },
  ];

  get filteredItems() {
    return this.items.filter((item) =>
      item.label.toLowerCase().includes(this.filter.toLowerCase())
    );
  }

  constructor(private cdr: ChangeDetectorRef) {}

  onFilterTextChanged(event: CustomEvent<string>) {
    this.filter = event.detail;
    this.remount();
  }

  private remount() {
    this.dropdownVisible = false;
    this.cdr.detectChanges();
    this.dropdownVisible = true;
    this.cdr.detectChanges();
  }
}

The critical parts are:

  1. Wrapping the component in @if:

    html@if (dropdownVisible) {
      <nv-fielddropdown ...>
    
  2. The remount() method that toggles visibility, forcing Angular to destroy and recreate the component:

    typescriptprivate remount() {
      this.dropdownVisible = false;
      this.cdr.detectChanges();
      this.dropdownVisible = true;
      this.cdr.detectChanges();
    }
    

Every time the filtered list changes, remount() is called, Angular tears down the old component and creates a new one, and Stencil slots everything correctly.

Using Signals (Angular 16+)

If you're using Angular signals, the pattern integrates naturally:

typescriptimport { Component, signal, computed, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-signal-example',
  template: `
    @if (dropdownVisible()) {
      <nv-fielddropdown
        [filterable]="true"
        [controlledFilter]="true"
        [value]="value()"
        (filterTextChanged)="onFilterTextChanged($event)"
        (valueChanged)="onValueChanged($event)">
        <ul slot="content">
          @for (item of filteredItems(); track item.value) {
            <nv-fielddropdownitem
              [label]="item.label"
              [value]="item.value">
            </nv-fielddropdownitem>
          }
        </ul>
      </nv-fielddropdown>
    }
  `,
})
export class SignalExampleComponent {
  filter = signal('');
  value = signal('');
  dropdownVisible = signal(true);

  items = signal([
    { label: 'Berlin', value: 'berlin' },
    { label: 'Hamburg', value: 'hamburg' },
    { label: 'Munich', value: 'munich' },
  ]);

  filteredItems = computed(() => {
    const lower = this.filter().toLowerCase();
    if (!lower) return this.items();
    return this.items().filter((item) =>
      item.label.toLowerCase().includes(lower)
    );
  });

  constructor(private cdr: ChangeDetectorRef) {}

  onFilterTextChanged(event: CustomEvent<string>) {
    this.filter.set(event.detail);
    this.remount();
  }

  onValueChanged(event: CustomEvent<string>) {
    this.value.set(event.detail);
  }

  private remount() {
    this.dropdownVisible.set(false);
    this.cdr.detectChanges();
    this.dropdownVisible.set(true);
    this.cdr.detectChanges();
  }
}

Alternative: Revision Counter with @if

Instead of a boolean toggle, you can use a revision counter combined with @if that always evaluates to true but changes identity on each increment. A simpler approach is to still use the toggle pattern but encapsulate it in a reusable method:

typescriptimport { Component, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-revision-example',
  template: `
    @if (dropdownVisible) {
      <nv-fielddropdown
        [filterable]="true"
        [controlledFilter]="true"
        [options]="filteredItems"
        (filterTextChanged)="onFilterTextChanged($event)"
        (valueChanged)="onValueChanged($event)">
        <ul slot="content">
          @if (filteredItems.length === 0) {
            <nv-fielddropdownitem [disabled]="true">
              No results found
            </nv-fielddropdownitem>
          }
        </ul>
      </nv-fielddropdown>
    }
  `,
})
export class RevisionExampleComponent {
  filter = '';
  selectedValue = '';
  dropdownVisible = true;

  items = [
    { label: 'Berlin', value: 'berlin' },
    { label: 'Hamburg', value: 'hamburg' },
    { label: 'Munich', value: 'munich' },
    { label: 'Frankfurt', value: 'frankfurt' },
    { label: 'Cologne', value: 'cologne' },
  ];

  get filteredItems() {
    if (!this.filter.trim()) return this.items;
    const lower = this.filter.toLowerCase();
    return this.items.filter((item) =>
      item.label.toLowerCase().includes(lower)
    );
  }

  constructor(private cdr: ChangeDetectorRef) {}

  onFilterTextChanged(event: CustomEvent<string>) {
    this.filter = event.detail;
    this.remount();
  }

  onValueChanged(event: CustomEvent<string>) {
    this.selectedValue = event.detail;
  }

  private remount() {
    this.dropdownVisible = false;
    this.cdr.detectChanges();
    this.dropdownVisible = true;
    this.cdr.detectChanges();
  }
}

Encapsulating the Pattern in a Utility

If you use this pattern frequently, consider extracting the remount logic into a reusable helper:

typescriptimport { ChangeDetectorRef } from '@angular/core';

/**
 * Creates a remount controller that can toggle a component out of
 * and back into the DOM to force Stencil to re-slot content.
 */
export function createRemountController(cdr: ChangeDetectorRef) {
  let visible = true;

  return {
    get visible() {
      return visible;
    },
    remount() {
      visible = false;
      cdr.detectChanges();
      visible = true;
      cdr.detectChanges();
    },
  };
}

Usage in a component:

typescriptimport { Component, ChangeDetectorRef } from '@angular/core';
import { createRemountController } from './remount-controller';

@Component({
  selector: 'app-utility-example',
  template: `
    @if (dropdown.visible) {
      <nv-fielddropdown
        [filterable]="true"
        [controlledFilter]="true"
        (filterTextChanged)="onFilterTextChanged($event)">
        <ul slot="content">
          @for (item of filteredItems; track item.value) {
            <nv-fielddropdownitem
              [label]="item.label"
              [value]="item.value">
            </nv-fielddropdownitem>
          }
        </ul>
      </nv-fielddropdown>
    }
  `,
})
export class UtilityExampleComponent {
  dropdown: ReturnType<typeof createRemountController>;
  filter = '';

  items = [
    { label: 'Berlin', value: 'berlin' },
    { label: 'Hamburg', value: 'hamburg' },
    { label: 'Munich', value: 'munich' },
  ];

  get filteredItems() {
    return this.items.filter((item) =>
      item.label.toLowerCase().includes(this.filter.toLowerCase())
    );
  }

  constructor(cdr: ChangeDetectorRef) {
    this.dropdown = createRemountController(cdr);
  }

  onFilterTextChanged(event: CustomEvent<string>) {
    this.filter = event.detail;
    this.dropdown.remount();
  }
}

When Is This Necessary?

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

ScenarioRemount needed?
Static list of itemsNo
Filtering / searching itemsYes
Adding or removing itemsYes
Reordering itemsYes
Changing props 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 the @if toggle 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 the parent component's properties.
  • Element references are reassigned. If you hold a ViewChild reference to the component, it will point to the new instance after re-mount. Be aware of this if you're caching the reference.
  • Performance. Re-mounting is more expensive than patching. For most use cases this is negligible, but avoid calling remount() unnecessarily if slot content hasn't actually changed.
  • Change detection. The remount() method calls ChangeDetectorRef.detectChanges() twice synchronously. This ensures Angular processes both the removal and the re-addition within the same call stack. This is intentional and necessary for the pattern to work.

Summary

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

When slot content changes dynamically, wrap the parent web component in @if and toggle it off and on using ChangeDetectorRef.detectChanges(). This forces Angular to re-create the component, keeping Angular and the web component in sync.

Related Documentation