diff --git a/packages/core/src/render3/view_ref.ts b/packages/core/src/render3/view_ref.ts index 096aa0c43b..b42a754297 100644 --- a/packages/core/src/render3/view_ref.ts +++ b/packages/core/src/render3/view_ref.ts @@ -60,8 +60,13 @@ export class ViewRef implements viewEngine_EmbeddedViewRef, viewEngine_Int destroy(): void { if (this._appRef) { this._appRef.detachView(this); - } else if (this._viewContainerRef && viewAttached(this._lView)) { - this._viewContainerRef.detach(this._viewContainerRef.indexOf(this)); + } else if (this._viewContainerRef) { + const index = this._viewContainerRef.indexOf(this); + + if (index > -1) { + this._viewContainerRef.detach(index); + } + this._viewContainerRef = null; } destroyLView(this._lView); diff --git a/packages/core/test/render3/view_container_ref_spec.ts b/packages/core/test/render3/view_container_ref_spec.ts index 0b0aeef96a..3312beeec5 100644 --- a/packages/core/test/render3/view_container_ref_spec.ts +++ b/packages/core/test/render3/view_container_ref_spec.ts @@ -19,7 +19,6 @@ import {pipe, pipeBind1} from '../../src/render3/pipe'; import {getLView} from '../../src/render3/state'; import {getNativeByIndex} from '../../src/render3/util'; import {NgForOf} from '../../test/render3/common_with_def'; -import {fixmeIvy} from '@angular/private/testing'; import {getRendererFactory2} from './imported_renderer2'; import {ComponentFixture, TemplateFixture, createComponent, getDirectiveOnNode} from './render_util'; @@ -1099,6 +1098,19 @@ describe('ViewContainerRef', () => { expect(dynamicComp.doCheckCount).toEqual(1); expect(changeDetector.context).toEqual(dynamicComp); }); + + it('should not throw when destroying a reattached component', () => { + const fixture = new ComponentFixture(AppComp); + + const dynamicCompFactory = fixture.component.cfr.resolveComponentFactory(DynamicComp); + const ref = fixture.component.vcr.createComponent(dynamicCompFactory); + fixture.update(); + + fixture.component.vcr.detach(fixture.component.vcr.indexOf(ref.hostView)); + + expect(() => { ref.destroy(); }).not.toThrow(); + + }); }); class EmbeddedComponentWithNgContent {