Skip to content

Commit

Permalink
feat(portal): allow custom ComponentFactoryResolver to be passed to C…
Browse files Browse the repository at this point in the history
…dkPortalOutlet

Adds the ability for consumers to pass in a different `ComponentFactoryResolver` when attaching to a `CdkPortalOutlet` programmatically.

Fixes #9712.
  • Loading branch information
crisbeto committed Feb 10, 2018
1 parent 008ee07 commit 8cdce40
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/cdk/portal/portal-directives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,15 @@ export class CdkPortalOutlet extends BasePortalOutlet implements OnInit, OnDestr
* Attach the given ComponentPortal to this PortalOutlet using the ComponentFactoryResolver.
*
* @param portal Portal to be attached to the portal outlet.
* @param componentFactoryResolver Alternate `ComponentFactoryResolver` to use when attaching the
* portal. Defaults to the resolver associated with the portal outlet instance.
* @returns Reference to the created component.
*/
attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> {
attachComponentPortal<T>(
portal: ComponentPortal<T>,
componentFactoryResolver: ComponentFactoryResolver = this._componentFactoryResolver):
ComponentRef<T> {

portal.setAttachedHost(this);

// If the portal specifies an origin, use that as the logical location of the component
Expand All @@ -142,8 +148,7 @@ export class CdkPortalOutlet extends BasePortalOutlet implements OnInit, OnDestr
portal.viewContainerRef :
this._viewContainerRef;

const componentFactory =
this._componentFactoryResolver.resolveComponentFactory(portal.component);
const componentFactory = componentFactoryResolver.resolveComponentFactory(portal.component);
const ref = viewContainerRef.createComponent(
componentFactory, viewContainerRef.length,
portal.injector || viewContainerRef.parentInjector);
Expand Down
15 changes: 15 additions & 0 deletions src/cdk/portal/portal.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,21 @@ describe('Portals', () => {
expect(instance.portalOutlet.hasAttached()).toBe(true);
});

it('should be able to use a custom component factory resolver',
inject([ComponentFactoryResolver], (resolver: ComponentFactoryResolver) => {
const testAppComponent = fixture.componentInstance;
const spy = jasmine.createSpy('resolveComponentFactorySpy');

testAppComponent.portalOutlet.attachComponentPortal(new ComponentPortal(PizzaMsg), {
resolveComponentFactory: (...args: any[]) => {
spy();
return resolver.resolveComponentFactory.apply(resolver, args);
}
});

expect(spy).toHaveBeenCalled();
}));

});

describe('DomPortalOutlet', () => {
Expand Down

0 comments on commit 8cdce40

Please sign in to comment.