Skip to content

Commit 7e08468

Browse files
andrewseguinjelbourn
authored andcommitted
fix(portal): cleanup PortalHost on directive destroy (#1703)
1 parent 8ce65ca commit 7e08468

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/lib/core/portal/portal-directives.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import {
55
Directive,
66
TemplateRef,
77
ComponentFactoryResolver,
8-
ViewContainerRef
8+
ViewContainerRef,
9+
OnDestroy
910
} from '@angular/core';
1011
import {Portal, TemplatePortal, ComponentPortal, BasePortalHost} from './portal';
1112

@@ -41,7 +42,7 @@ export class TemplatePortalDirective extends TemplatePortal {
4142
selector: '[portalHost]',
4243
inputs: ['portal: portalHost']
4344
})
44-
export class PortalHostDirective extends BasePortalHost {
45+
export class PortalHostDirective extends BasePortalHost implements OnDestroy {
4546
/** The attached portal. */
4647
private _portal: Portal<any>;
4748

@@ -59,7 +60,11 @@ export class PortalHostDirective extends BasePortalHost {
5960
this._replaceAttachedPortal(p);
6061
}
6162

62-
/** Attach the given ComponentPortal to this PortlHost using the ComponentFactoryResolver. */
63+
ngOnDestroy() {
64+
this.dispose();
65+
}
66+
67+
/** Attach the given ComponentPortal to this PortalHost using the ComponentFactoryResolver. */
6368
attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> {
6469
portal.setAttachedHost(this);
6570

src/lib/core/portal/portal.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,18 @@ describe('Portals', () => {
4343
expect(hostContainer.textContent).toContain('Pizza');
4444
});
4545

46+
it('should dispose the host when destroyed', () => {
47+
// Set the selectedHost to be a ComponentPortal.
48+
let testAppComponent = fixture.debugElement.componentInstance;
49+
testAppComponent.selectedPortal = new ComponentPortal(PizzaMsg);
50+
51+
fixture.detectChanges();
52+
expect(testAppComponent.selectedPortal.isAttached).toBe(true);
53+
54+
fixture.destroy();
55+
expect(testAppComponent.selectedPortal.isAttached).toBe(false);
56+
});
57+
4658
it('should load a component into the portal with a given injector', () => {
4759
// Create a custom injector for the component.
4860
let chocolateInjector = new ChocolateInjector(fixture.componentInstance.injector);

0 commit comments

Comments
 (0)