How to set context on an Angular [cdkPortalOutlet]

Discussão em 'Angular' iniciado por Simon_Weaver, Janeiro 20, 2025.

  1. Simon_Weaver

    Simon_Weaver Guest

    The Portal module in Angular Material (CDK) is a very powerful way to render dynamic content into a 'PortalOutlet'.

    A Portal<T> can be a TemplateRef where T is the type of the context data.

    <ng-template cdkPortal let-data>
    <p>Portal contents {{ data | json }}</p>
    </ng-template>


    You get a reference to it with @ViewChild

    @ViewChild(CdkPortal) myPortalRef: CdkPortal;


    You can display a portal in a cdkPortalOutlet

    Content gets inserted here:
    <ng-template [cdkPortalOutlet]="myPortalRef"></ng-template>


    This will insert the portal contents into the outlet.

    But there are two big missing features with the provided directives.

    1) no way to set the actual context object on the outlet using the directive
    2) no way to set the context object on the portal itself


    You can manually create an portal and provide a context, or attach a Portal to a PortalOutlet programatically with a context but I want to do it more declaratively.

    The similar (and more commonly used) [NgTemplateOutlet] does provide a property for [ngTemplateOutletContext].

    What's the best way to set context on a CdkPortal? Should I extend the directives myself, or try to pass through my data with a service? I thought the whole point of this module was to make things super easy.

    Angular source

    See also: https://github.com/angular/material2/issues/6310

    Continue reading...

Compartilhe esta Página