Using dynamic selector for ng-content

Discussão em 'Angular' iniciado por Link, Outubro 23, 2024.

  1. Link

    Link Guest

    I am trying to create a component that can host multiple ng-content with different selectors. The usage might be something like this:

    <app-sub #sub>
    <div fullscreen>
    <p>Fullscreen</p>
    </div>
    <div id="test">
    <p>Some other content</p>
    </div>
    </app-sub>


    Where the user can toggle between the different screens:

    <button (click)="sub.toggle('test')">Switch to test</button>
    <button (click)="sub.toggle()">Switch to fullscreen</button>


    For this I built the component that should be capable of doing this:

    @if (!activeId) {
    <p>In Non Active</p>
    <ng-content select="[fullscreen]"></ng-content>
    } @else {
    <p>In Active with: {{activeId}}</p>
    <ng-content select="[id={{activeId}}]"></ng-content>
    }


    With the toggle:

    export class SubComponent {
    protected activeId?: string;

    public toggle(id?: string) {
    this.activeId = id;
    }
    }


    While the fullscreen content is shown, selecting by the id doesn't work. But if I predefined the id in the "sub" component as such:

    <ng-content select="#test"></ng-content>
    <!-- or -->
    <ng-content select="[id='test']"></ng-content>


    Then it works. So basically setting the values at compile time rather than runtime.

    How can I achieve that I can select components dynamically?

    Here is a stackblitz to play around: https://stackblitz.com/edit/stackblitz-starters-brmda7

    Continue reading...

Compartilhe esta Página