Angular: Bootstrapping in angular

What is Bootstrapping?

Bootstrapping is a technique of initializing or loading our Angular application. Let’s walk through the code created in "Create your First new Angular project" and see what happens at each stage and how our AppComponent gets loaded and displays “app works!”. Angular takes the following steps to load our first view:

  1. Index.html loads: The initial HTML file is loaded into the browser.
  2. Angular, Third-party libraries & Application loads: Angular framework and any third-party libraries are loaded.
  3. Main.ts - the application entry point: The main.ts file is executed, which bootstraps the Angular application.
  4. Root Module: The root module (AppModule) is loaded. This module organizes the application code and defines the components, services, and other features used in the application.
  5. Root Component: The root component (AppComponent) is loaded. This component serves as the starting point of the application and is defined in the root module.
  6. Template: The template associated with the root component is loaded and rendered. In this case, the template is defined in the app.component.html file.

Index.html Loads First

Web apps need a starting point. index.html is usually the first page to load. Let us open the file and find out what it contains. You will find it under the src folder.

There are no JavaScript files in the index.html, and you cannot see a stylesheet file. The body of the file has the following HTML tag:

    
      <app-root></app-root>
    
  

Building Application

To run our application, we use:

  • The Angular CLI command ng serve
  • Or NPM command npm start (npm start command actually translates into ng serve.)

ng serve does build our application but does not save the compiled application to the disk. It saves it in memory and starts the development server. We use ng build to build our app. Open the command prompt and run the command. This will build and copy the output files to the dist folder:

    
      ng build
    
  

Use ng build --prod to build and distribute the app for production. For testing/debugging, use ng build. The production build optimizes, minimizes, and uglifies the code. Now open the dist and open the index.html:

    
      <!doctype html>
      <html lang="en">

      <head>
        <meta charset="utf-8">
        <title>GettingStarted</title>
        <base href="/">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" type="image/x-icon" href="favicon.ico">
      </head>

      <body>
        <app-root></app-root>

        <script src="runtime-es2015.js" type="module"></script>
        <script src="runtime-es5.js" nomodule defer></script>
        <script src="polyfills-es5.js" nomodule defer></script>
        <script src="polyfills-es2015.js" type="module"></script>
        <script src="styles-es2015.js" type="module"></script>
        <script src="styles-es5.js" nomodule defer></script>
        <script src="vendor-es2015.js" type="module"></script>
        <script src="vendor-es5.js" nomodule defer></script>
        <script src="main-es2015.js" type="module"></script>
        <script src="main-es5.js" nomodule defer></script>
      </body>

      </html>

    
  

You can see that the compiler included five script files. They are runtime, polyfills, styles, vendor, and main. All these files have two versions:

  • One is es5
  • The other one is es2015

These files are added by the Webpack module loader:

  • runtime.js: Webpack runtime file
  • polyfills.js: Polyfill scripts for supporting the variety of the latest modern browsers
  • styles.js: This file contains the global style rules bundled as a javascript file.
  • vendor.js: Contains the scripts from the Angular core library and any other 3rd party library.
  • main.js: Code of the application.

What is Webpack?

Webpack is a bundler. It scans our application looking for JavaScript files and merges them into one (or more) big file. Webpack has the ability to bundle any kind of file like JavaScript, CSS, SASS, LESS, images, HTML, & fonts, etc. The Angular CLI uses Webpack as a module bundler. Webpack needs a lot of configuration options to work correctly, and the Angular CLI sets up all these configuration options behind the scenes. Webpack traverses through our application looking for JavaScript and other files and merges all of them into one or more bundles.

Application Loads

When index.html is loaded, the Angular core libraries and third-party libraries are loaded. Now Angular needs to locate the entry point.

Application Entry point

The entry point of our application is main.ts. You will find it under the src folder.

    
      import { enableProdMode } from '@angular/core';
      import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

      import { AppModule } from './app/app.module';
      import { environment } from './environments/environment';

      if (environment.production) {
        enableProdMode();
      }

      platformBrowserDynamic().bootstrapModule(AppModule)
        .catch(err => console.error(err));
    
  

angular.json

The Angular finds out the entry point from the configuration file angular.json. This file is located in the root folder of the project. The relevant part of the angular.json is shown below:

    
      {
        "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
        "version": 1,
        "newProjectRoot": "projects",
        "projects": {
          "GettingStarted": {
            "projectType": "application",
            "schematics": {},
            "root": "",
            "sourceRoot": "src",
            "prefix": "app",
            "architect": {
              "build": {
                "builder": "@angular-devkit/build-angular:browser",
                "options": {
                  "outputPath": "dist/GettingStarted",
                  "index": "src/index.html",
                  "main": "src/main.ts",
                  "polyfills": "src/polyfills.ts",
                  "tsConfig": "tsconfig.app.json",
                  "aot": false,
                  "assets": [
                    "src/favicon.ico",
                    "src/assets"
                  ],
                  "styles": [
                    "src/styles.css"
                  ],
                  "scripts": []
                },
              }
            }
          }
        }
      }
    
  

The main entry under the node:

  • projects -> GettingStarted -> architect -> build -> options points towards the src/main.ts. This file is the entry point of our application.

main.ts - Application Entry Point

Let us look at the relevant code in detail:

    
      import { enableProdMode } from '@angular/core';
      import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
      
      import { AppModule } from './app/app.module';
      import { environment } from './environments/environment';
      
      if (environment.production) {
        enableProdMode();
      }
      
      platformBrowserDynamic().bootstrapModule(AppModule)
        .catch(err => console.error(err));
    
  

This code does the following:

  • import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - This line imports the module platformBrowserDynamic from the library @angular/platform-browser-dynamic.

platformBrowserDynamic

platformBrowserDynamic is the module responsible for loading the Angular application in the desktop browser. Angular applications can be bootstrapped in various ways and on different platforms. For example:

  • We can load our application in a desktop browser.
  • We can load it on a mobile device with Ionic or NativeScript.

If you are using NativeScript, then you would use platformNativeScriptDynamic from nativescript-angular/platform library and call platformNativeScriptDynamic().bootstrapModule(AppModule).

    
      import { AppModule } from './app/app.module';

      // The above line imports AppModule.
      // The AppModule is the Root Module of the app.
      // Angular applications are organized as modules, and every Angular app must have at least one module.
      // The module loaded first when the application starts is called the root module.

      platformBrowserDynamic().bootstrapModule(AppModule)
        .catch(err => console.error(err));
      
      // The platformBrowserDynamic loads the root module by invoking bootstrapModule and providing it a reference to our Root module, i.e., AppModule.
    
  

Root Module (AppModule)

The Angular bootstrapper loads our root module AppModule, located under the folder src/app.

    
      import { BrowserModule } from '@angular/platform-browser';
      import { NgModule } from '@angular/core';
      
      import { AppRoutingModule } from './app-routing.module';
      import { AppComponent } from './app.component';
      
      @NgModule({
        declarations: [
          AppComponent
        ],
        imports: [
          BrowserModule,
          AppRoutingModule
        ],
        providers: [],
        bootstrap: [AppComponent]
      })
      export class AppModule { }
    
  

The root module (AppModule) must have at least one root component. The root component is loaded when the module is loaded by Angular. In our example, AppComponent is our root component, so we import it:

    
      import { AppComponent } from './app.component';
    
  

We use the @NgModule class decorator to define a module and provide metadata about the module:

    
      @NgModule({
        declarations: [
          AppComponent
        ],
        imports: [
          BrowserModule,
          AppRoutingModule
        ],
        providers: [],
        bootstrap: [AppComponent]
      })
      export class AppModule { }
    
  

The @NgModule decorator has several metadata properties:

  • imports: We need to list all the external modules required, including other Angular modules used by this Angular module.
  • declarations: The declarations array contains the list of components, directives, pipes, and services. In our case, we have only one component, AppComponent.
  • bootstrap: Specifies the component that Angular should load when this Angular module loads. The component must be part of this module. We want AppComponent to load when AppModule loads, so we list it here. Angular reads the bootstrap metadata and loads AppComponent.

Component (AppComponent)

AppComponent is the root component of the AppModule. The code for our AppComponent is shown below:

    
      import { Component } from '@angular/core';
      
      @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      export class AppComponent {
        title = 'GettingStarted';
      }
    
  

The AppComponent class is decorated with the @Component class decorator. This decorator provides metadata about the class to Angular and has three properties in the above code:

  • selector: This property specifies the CSS selector where our template will be inserted into the HTML. The CSS selector in our code is app-root.
  • templateUrl: This property contains an HTML template, which is going to be displayed in the browser. The template file is app.component.html.
  • styleUrls: This property is an array of style sheets that Angular uses to style our HTML file. In the above example, it points to the app.component.css style sheet. The app.component.css file is in the same folder as the AppComponent.

Template

The AppComponent defines the template as app.component.html, and the CSS selector is app-root.

Our index.html already has the app-root CSS selector defined:

    
      <body>
        <app-root></app-root>
      </body>
    
  

The Angular locates app-root in our index.html and renders our template between those tags.

Single page application(SPA)

Comments

Popular posts from this blog

Car Wash System vb.net

Student Information System - AngularJS , ASP.NET API, C#

Fake Call Android Application