问题
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
回答1:
I think you can assign the context directly to the portal but I haven't tested this. It has to be assigned before the outlet uses the portal and that might be tricky.
@ViewChild(CdkPortal) myPortalRef: CdkPortal;
public ngAfterViewInit(): void {
this.myPortalRef.context = {...}; // your context data
}
I think the issue here is that the context is attached to the portal instead of being independant. So you can't use the same portal to render in two different outlets with two different contexts.
Also, have you tried using cdkPortalOutlet
with the micro-syntax parser in Angular to see if it works?
<ng-template *cdkPortalOutlet="myPortalRef; context: contextExp"></ng-template>
From what I can tell the ng-template
methods for the portals isn't used in the library. Everything with portals is done as services, and the template variant appears to have been an add on feature for the community but it wasn't fully vetted.
来源:https://stackoverflow.com/questions/51803125/how-to-set-context-on-an-angular-cdkportaloutlet