From 7e084681b3227ef079713ff3cddf33b94368901d Mon Sep 17 00:00:00 2001 From: Andrew Seguin Date: Thu, 3 Nov 2016 15:53:46 -0700 Subject: [PATCH] fix(portal): cleanup PortalHost on directive destroy (#1703) --- src/lib/core/portal/portal-directives.ts | 11 ++++++++--- src/lib/core/portal/portal.spec.ts | 12 ++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/lib/core/portal/portal-directives.ts b/src/lib/core/portal/portal-directives.ts index 401d96502f4e..dab58967322e 100644 --- a/src/lib/core/portal/portal-directives.ts +++ b/src/lib/core/portal/portal-directives.ts @@ -5,7 +5,8 @@ import { Directive, TemplateRef, ComponentFactoryResolver, - ViewContainerRef + ViewContainerRef, + OnDestroy } from '@angular/core'; import {Portal, TemplatePortal, ComponentPortal, BasePortalHost} from './portal'; @@ -41,7 +42,7 @@ export class TemplatePortalDirective extends TemplatePortal { selector: '[portalHost]', inputs: ['portal: portalHost'] }) -export class PortalHostDirective extends BasePortalHost { +export class PortalHostDirective extends BasePortalHost implements OnDestroy { /** The attached portal. */ private _portal: Portal; @@ -59,7 +60,11 @@ export class PortalHostDirective extends BasePortalHost { this._replaceAttachedPortal(p); } - /** Attach the given ComponentPortal to this PortlHost using the ComponentFactoryResolver. */ + ngOnDestroy() { + this.dispose(); + } + + /** Attach the given ComponentPortal to this PortalHost using the ComponentFactoryResolver. */ attachComponentPortal(portal: ComponentPortal): ComponentRef { portal.setAttachedHost(this); diff --git a/src/lib/core/portal/portal.spec.ts b/src/lib/core/portal/portal.spec.ts index 6f9c176f3c8a..6f51d1ef686d 100644 --- a/src/lib/core/portal/portal.spec.ts +++ b/src/lib/core/portal/portal.spec.ts @@ -43,6 +43,18 @@ describe('Portals', () => { expect(hostContainer.textContent).toContain('Pizza'); }); + it('should dispose the host when destroyed', () => { + // Set the selectedHost to be a ComponentPortal. + let testAppComponent = fixture.debugElement.componentInstance; + testAppComponent.selectedPortal = new ComponentPortal(PizzaMsg); + + fixture.detectChanges(); + expect(testAppComponent.selectedPortal.isAttached).toBe(true); + + fixture.destroy(); + expect(testAppComponent.selectedPortal.isAttached).toBe(false); + }); + it('should load a component into the portal with a given injector', () => { // Create a custom injector for the component. let chocolateInjector = new ChocolateInjector(fixture.componentInstance.injector);