angular

By default, an Angular application is initialized automatically by loading the angular.js script and placing the ng-app directive to the root element of your application (e.g. <html> tag), like the following:

Explore Angular Courses

Alternatively, you can also initialize your application manually if you need, using the angular.bootstrap() function. This is especially useful when you want your application to initialize only after a certain period or bound to another event taking place. See this page for further details about the initialization methods in Angular.

How to Use angular.bootstrap

angular.bootstrap is a function component in the core ng module that is used for starting up the Angular application manually, which gives you more control over how you initialize your application. The syntax for angular.bootstrap is as follows:

element is a DOM element (e.g. document) that is the root of the Angular application, modules (optional) is an array of modules to be loaded and config (optional) is an object used for configuration options. You can check this page on the official developer guide to read more about angular.bootstrap syntax.

Example 1: Manually Bootstrap Your Angular Application

In the following example, we manually bootstrap our application which displays a welcome message once the user logs in.

Note how we selected document as the root of the application and how we passed the example module to the angular.bootstrap() function.

Example 2: Bootstrap by Selecting a Specific Element

In the following example, we will display the current year in our application and bootstrap it by selecting a specific element as the application root.

We selected the div element with the id #year as the root of our application.

Example 3: Bootstrap Multiple Applications

Explore Angular Courses

Using the angular.bootstrap function, you can bootstrap multiple angular applications on a single page. Let’s say we have two applications (app1 and app2) defined by two div elements:

We use the following code to start up these two applications:

Before ending this tutorial, we will list a number of things you should pay attention while manually starting your applications using angular.bootstrap.

  • If you use angular.bootstrap to start your application, you shouldn’t use the ng-app directive.
  • You need to create the custom modules before passing them as a parameter to angular.bootstrap().
  • When using multiple bootstraps on the same page, use them cautiously.

Comments