Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you remove the Angular root element

Tags:

angular

I'm manually bootstrapping an Angular application.

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

When the root element is removed from the DOM I wait for it to be injected again and manually bootstrap the application another time. This happens many, many times. (I'm using Angular within a larger app...).

So far it works well but I'm concerned that simply removing the element isn't going to clean things up. Is there anything else I should do to 'unbootstrap' the application?

like image 338
nick Avatar asked Dec 10 '18 13:12

nick


1 Answers

The best you can do is check the bootstrap method implementation in the Angular source code.

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

Here are the main points of interest (part of the code is omitted for clarity):

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;
}

You can see that each time on bootstrap a component with a new injector is created. On destroy this._unloadComponent destroys the associated view and component instances. If you're unsure if onDestroy is triggered on element's removal, you can trigger it yourself on the component ref that is returned by a bootstrap method:

const compRef: ComponentRef<AppComponent> = app.bootstrap(AppComponent);
// some time later
compRef.destroy();
like image 85
Evgeniy Malyutin Avatar answered Sep 27 '22 17:09

Evgeniy Malyutin