23 May 2017
2 min

Hooking into the Angular bootstrap process

Angular provides several mechanisms to hook into initialization process. This article explores them and shows how they can be used.

APP_BOOTSTRAP_LISTENER

It is possible to register listeners for the Angular bootstrap process. Here is the code where they are called:

private _loadComponent(componentRef: ComponentRef<any>): void {
  this.attachView(componentRef.hostView);
  this.tick();
  this._rootComponents.push(componentRef);
  // Get the listeners lazily to prevent DI cycles.
  const listeners =
      this._injector.get(APP_BOOTSTRAP_LISTENER, []).concat(this._bootstrapListeners);
  listeners.forEach((listener) => listener(componentRef));
}

This is the function that Angular calls when instantiating the application. Besides giving insights into how a component is added into the application, it also suggests that for each bootstrapped component Angular calls listeners registered under APP_BOOTSTRAP_LISTENER token and passes bootstrapped component to them.

It means that we can use such hooks to subscribe to the application bootstrap process and perform our initialization logic. For example, here is how Router hooks into to the process and executes some initialization.

Since Angular passes initialized component into the callback, we can get hold of root ComponentRef of the application like this:

import {APP_BOOTSTRAP_LISTENER, ...} from '@angular/core';
@NgModule({
  imports: [BrowserModule, ReactiveFormsModule, TasksModule],
  declarations: [AppComponent, BComponent, AComponent, SComponent, LiteralsComponent],
  providers: [{
    provide: APP_BOOTSTRAP_LISTENER, multi: true, useFactory: () => {
      return (component: ComponentRef<any>) => {
        console.log(component.instance.title);
      }
    }
  }],
  bootstrap: [AppComponent]
})
export class AppModule {}

After running into such functionality in the sources I checked the documentation and it’s described as experimental and the following description is provided:

All callbacks provided via this token will be called for every component that is bootstrapped. Signature of the callback: (componentRef: ComponentRef) => void

APP_INITIALIZER

Angular also provides a mechanism to perform some initialization logic before it declares the application as initialized and continues with change detection and template rendering. This is where this initialization takes place:

constructor(@Inject(APP_INITIALIZER) @Optional() appInits: (() => any)[]) {
  const asyncInitPromises: Promise<any>[] = [];
  if (appInits) {
    for (let i = 0; i < appInits.length; i++) {
      const initResult = appInits[i]();
      if (isPromise(initResult)) {
        asyncInitPromises.push(initResult);
      }
    }
  }

So, the same way we did it for the APP_BOOTSTRAP_LISTENER token, we just define APP_INITIALIZER provider and our function will be called. The following example delays Angular initialization for 5 seconds:

{
  provide: APP_INITIALIZER,
  useFactory: () => {
    return () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, 5000);
      });
    }
  },
  multi: true
}

And you can define multiple APP_INITIALIZER’s like this:

{
  provide: APP_INITIALIZER,
  useFactory: () => {
    return () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, 5000);
      });
    }
  },
  multi: true
},
{
  provide: APP_INITIALIZER,
  useFactory: () => {
    return () => {
      return new Promise.resolve(2);
    }
  },
  multi: true
}

BootstrapModule

Another point where you can hook into the application bootstrap process is bootstrapModule method:

platform.bootstrapModule(AppModule).then((module) => {
  let applicationRef = module.injector.get(ApplicationRef);
  let rootComponentRef = applicationRef.components[0];
});

Here you can get NgModuleRef to the bootstrapped module through which you can access ApplicationRef and ComponentRef.

Frequently asked questions

How do I run initialization code before an Angular app starts rendering?

Register an APP_INITIALIZER provider whose factory returns an initialization function. Angular calls that function before declaring the application initialized and continuing with change detection and template rendering. The function can return a Promise for asynchronous work, such as loading data or configuration before the app proceeds.

What is the difference between APP_INITIALIZER and APP_BOOTSTRAP_LISTENER in Angular?

APP_INITIALIZER runs initialization logic before Angular declares the application initialized, while APP_BOOTSTRAP_LISTENER runs after a component has been bootstrapped. An initializer is suited to work that must happen before rendering continues; a bootstrap listener receives the bootstrapped ComponentRef and can react to that component being added.

How can I delay Angular initialization with APP_INITIALIZER?

Return a Promise from the function provided by APP_INITIALIZER; Angular waits for the asynchronous initialization to complete before proceeding. For example, the article uses a promise resolved by setTimeout after five seconds. This pattern can defer application initialization while asynchronous work finishes.

Can I register multiple APP_INITIALIZER providers in Angular?

Yes. Register each initializer as a separate provider with multi: true, so they are collected under the APP_INITIALIZER token. The article demonstrates multiple providers, including one that returns a promise resolved after a delay and another that returns a resolved promise.

How do I access a bootstrapped component with APP_BOOTSTRAP_LISTENER?

Provide APP_BOOTSTRAP_LISTENER with multi: true and return a callback that accepts a ComponentRef. Angular calls the callback for each bootstrapped component, so the callback can access the component instance through component.instance. The article notes that the token is described as experimental in the documentation it references.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.