Follow by Email

Angular 2 - Bootstrapping the module for the browser



With an Angular root module and a starting component created, the next step to getting the foundation of an Angular app up and running is the code to bootstrap the module. 
We can add a file named main.ts to the app folder and put the bootstrap logic in that file. 

Angular actually has support for running on multiple platforms. The browser is considered a platform. 

The server and web worker are examples of other platforms. Other third-party bootstraps could also be used to provide support for other platforms. 

For this app, we are targeting the browser, so we need to bootstrap from that platform. 

Angular exports a platformBrowserDynamic function for targeting the browser from the platformBrowserDynamic-scoped package. So we can import platformBrowserDynamic from there. This function returns a platform object that has a bootstrap module function on it. That is the function you will use to bootstrap your root module on the platform. Note that earlier we were importing class types, and here we are importing a function. 



import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);




The module-loading syntax supports importing all kinds of exported things, from class types and functions to constants, variables, and even JSON file data. 

Okay, so now we can make the call to the platformBrowserDynamic function which will return an instance of a platform object. That platform object has a method named bootstrapModule. So off of that platformBrowserDynamic call, we can call bootstrapModule

This function is expecting a root module and we have one already created from earlier named AppModule. So we can go up and write an import statement to load that type into this file, and then we can pass the AppModule type into the bootstrapModule function call. And with that, we have all the initial starting bits written to get this Angular app up and running in the browser. Let's open up a command line or terminal. 




And we can run the npm start command to kick off the TypeScript build and web server and we'll watch for changes. And over in the browser, we can see the content from the app component template is displayed. So for the remaining videos going forward, if you are following along with the Exercise Files locally, you can run the npm start command to start up the site and have it reload as you change code.