Skip to main content

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

This software consists of a database that save the registration number of every vehicle being wash along side with the date, type of wash made and price Screen Shot Source Code To view records in the database: Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\washRcd.accdb;Persist Security Info=False") Dim sql As String sql = " SELECT * FROM tblwash" conn.Open() Dim dt As New DataTable Dim cmd2 As New OleDb.OleDbDataAdapter(sql, conn) cmd2.Fill(dt) DataGridView1.DataSource = dt DataGridView1.Refresh() conn.Close() To insert new record in the database: Private Sub insert() Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\washRcd.accdb;Persist Security Info=False") Dim updateSql As String = String.Format(...

Face recognition using EmguCV 3.0 and typing pattern recognition

Introduction An MSc project with the title Student Examination System, where the objective is to put the students in an examination condition but instead of having an invigilator in an examination center, the system will cater for the proper ongoing of the exam. the system can be used as an online examination system The system is able to: Recognizing the face shape of a particular student Detect if there is more than one person in the examination room  Analyze the typing pattern of a student and detect if any one person is taking part in the exam voice recognition for the student and detect if there is more than one person speaking in the examination room Setup Download Emgu CV from  http://www.emgu.com/wiki/index.php/Main_Page Download Haarcascade from  https://github.com/opencv/opencv/tree/master/data/haarcascades Create an account at  https://www.keytrac.net/ Face recognition The snippet below illustrates how the Emgu CV is loaded whe...

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

Web based application the student information system is a small application that allows user to register and login to view information about a particular student and can perform several actions like Login and register to the application View students  Add new student Delete a particular student Update user information Screen Shot Project architecture routing.js, config.js and app.js allow the application to route from one partial view to another and config.js is used to save all the endpoint needed to access the API.   For separation of concerns, in the solution panel separate partial views, controller and services in different directories and reference it in index.html to enable angular to load all the files required Login process login.html LoginController.js Using $resource from AngularJS to make an API call and response  with a user details model UserViewModel and UserDetailsViewModel Using Unity fo...