Angular Compound Dropdown Component Loses Selection on Subsequent Choices

Discussão em 'Angular' iniciado por Devarshi Roy, Abril 12, 2025.

  1. Devarshi Roy

    Devarshi Roy Guest

    I'm creating a compound dropdown component in Angular where items can contain custom components. The initial selection works, but subsequent selections clear the previous choice. Here's my implementation:

    Dropdown Component (app-dropdown):

    import { DropdownitemComponent } from './dropdownitem.component';

    @Component({
    selector: 'app-dropdown',
    template: `
    <div class="dropdown-container">
    <div class="selected-area" (click)="toggleOpen()">
    <ng-container #selectedContainer></ng-container>
    <span *ngIf="!selectedView">Please select</span>
    </div>

    <div class="items-container" *ngIf="isOpen">
    <div class="dropdown-item"
    *ngFor="let item of items"
    (click)="selectItem(item)">
    <ng-container *ngTemplateOutlet="item.contentTemplate"></ng-container>
    </div>
    </div>
    </div>
    `
    })
    export class DropdownComponent {
    isOpen = false;
    selectedView: any;

    @ContentChildren(DropdownitemComponent) items!: QueryList<DropdownitemComponent>;
    @ViewChild('selectedContainer', { read: ViewContainerRef }) selectedContainer!: ViewContainerRef;

    toggleOpen() { this.isOpen = !this.isOpen; }

    selectItem(item: DropdownitemComponent) {
    this.selectedContainer.clear();
    this.selectedView = item.contentTemplate.createEmbeddedView({});
    this.selectedContainer.insert(this.selectedView);
    this.isOpen = false;
    }
    }

    Dropdown Item Component (app-dropdownitem):

    import { Component, TemplateRef, ViewChild } from '@angular/core';

    @Component({
    selector: 'app-dropdownitem',
    template: `
    <ng-template #contentTemplate>
    <ng-content></ng-content>
    </ng-template>
    `
    })
    export class DropdownitemComponent {
    @ViewChild('contentTemplate') contentTemplate!: TemplateRef<any>;
    }

    Usage:

    <app-dropdown>
    <app-dropdownitem>
    <app-custom-component></app-custom-component>
    </app-dropdownitem>
    <app-dropdownitem>
    <div class="custom-item">Test</div>
    </app-dropdownitem>
    </app-dropdown>


    The Problem:


    What I've Tried:

    Using *ngTemplateOutlet directly

    Tracking by index instead of template references

    Angular CDK Portal approach

    Manual view management with ViewContainerRef

    Key Requirements:

    Must support arbitrary components in dropdown items

    Selected item should fully render its content

    Compound component pattern must be maintained

    Why does the selection fail after the first choice? How can I make selections persist across multiple interactions while maintaining the compound component structure?

    Continue reading...

Compartilhe esta Página