删除Angular根元素会发生什么

时间:2018-12-10 13:45:31

标签: angular

我正在手动引导Angular应用程序。

ngDoBootstrap(app) {
    app.bootstrap(AppComponent);
}

当从DOM中删除根元素时,我等待它再次被注入并再次手动引导应用程序。这发生了很多很多次。 (我在更大的应用程序中使用Angular ...)。

到目前为止,它运作良好,但我担心仅删除元素不会清理一切。我还应该采取其他措施来“取消引导”应用程序吗?

1 个答案:

答案 0 :(得分:3)

最好的办法是检查Angular源代码中的bootstrap方法实现。

https://github.com/angular/angular/blob/44dd764d6d6582d92d3709501258cdb51c3ea85d/packages/core/src/application_ref.ts#L453

主要景点(为清楚起见,省略了部分代码):

bootstrap<C>(componentOrFactory: ComponentFactory<C>|Type<C>, rootSelectorOrNode?: string|any): ComponentRef<C> {
    const compRef = componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);

    compRef.onDestroy(() => { this._unloadComponent(compRef); });

    this._loadComponent(compRef);

    return compRef;
}

您可以看到,每次引导时都会创建带有新进样器的组件。开时销毁this._unloadComponent销毁关联的视图和组件实例。如果不确定onDestroy是否在元素移除时触发,则可以自己在引导方法返回的组件ref上触发它:

const compRef: ComponentRef<AppComponent> = app.bootstrap(AppComponent);
// some time later
compRef.destroy();
相关问题