ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Bootstrapping in Angular: How It Works Internally

In this article on Bootstrapping in Angular, let us find out how Angular works internally and bootstraps our app. We used ng new to create a new Angular project. It generates lots of boilerplate codes. It also configures the Typescript, Webpack & Karma. The app, when run, displays a simple HTML page with several useful links to Angular. Now let us break up this app and look at what happens when the app starts until it displays the HTML page

Create a new Angular Application

We’ll start with a new application to learn how Angular works internally.

Install Angular and run the following command to create a new Angular application.

                              
ng new GettingStarted
                            
                        

You can run the app using the following command, which will compile and run the app.

                              
ng serve --open
                            
                        
Image

Bootstrapping in Angular

What is a Bootstrapping

Bootstrapping is the process of initializing or loading our Angular application.

Angular takes the following steps to load our first view.

  1. Loads Index.html
  2. Loads Angular & Third-party libraries & Application
  3. Executes application entry point (main.ts)
  4. Load & execute Root Module (app.module.ts)
  5. Executes the Root Component (app.component.ts)
  6. Displayes the template (app.component.html)

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.

                              
<!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>
</body>
</html>
                            
                        

There are no javascript files in the index.html. Neither there is a stylesheet file. The body of the files has the following HTML tag.

                              
<app-root></app-root>
                            
                        

How do Angular loads? To find out, let us build our application

Building Application

To run our application, we use the Angular CLI command ng serve.

ng serve builds our application but does not save the compiled application to the disk. It saves it in memory and starts the development server. ng serve also watches over the project. If we make any changes to the application, it will re-compile and update the file.

To view the compiled application, we need to build the project. We can do that using the ng build. Open the command prompt and run the ng build command. This will build and copy the output files to the dist\getting-started folder (Older versions copied the files to the dist folder).

                              

ng build
 
                            
                        

Now open the dist\getting-started 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" />
    <link rel="stylesheet" href="styles.56e3e15f5d5be678.css" />
  </head>
  <body>
    <app-root></app-root>
    <script src="runtime.87dd532f2ee308a5.js" type="module"></script>
    <script src="polyfills.96a2a660c10c5395.js" type="module"></script>
    <script src="main.6ea3cc439cb6e266.js" type="module"></script>
  </body>
</html>
 
                            
                        

You can see that the compiler included four script files. They are runtime, polyfills, styles, & main.

runtime.js: Webpack runtime file
polyfills.js – 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.

The Webpack module loader adds these files.

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. The Angular CLI sets up all these configuration options behind the scene.

The Angular CLI uses Webpack as a module bundler. Webpack needs a lot of configuration options to work correctly. The Angular CLI sets up all these configuration options behind the scene.

The Webpack traverses through our application, looking for javascript and other files, and merges all of them into one or more bundles. In our example application, it has created five files.

Loads Angular & Third-party libraries & Application

So when index.html is loaded, the Angular core libraries and third-party libraries are loaded. Now the 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.

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 from 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/getting-started",
            "index": "src/index.html",
            "main": "src/main.ts",              ===>
            "polyfills": [
              "zone.js"
            ],
                            
                        

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

Application entry point (main.ts)

The main.ts file is shown below.

                              

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

Let us look at the relevant code in detail.

                              

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

This line imports the module platformBrowserDynamic from the library@angular/platform-browser-dynamic.

What is platformBrowserDynamic

platformBrowserDynamic is the module responsible for loading the Angular application in the desktop browser?

Angular Applications can be bootstrapped in many ways and in many platforms. For example, we can load our application in a Desktop Browser or in a mobile device with Ionic or NativeScript.

If you are using the nativescript, then you will be using platformNativeScriptDynamic it from nativescript-angular/platform library and will be calling platformNativeScriptDynamic().bootstrapModule(AppModule). Read more about the Angular Nativescript bootstrap process here.

                              

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

The above line imports AppModule. The AppModule is the Root Module of the app. The Angular applications are organized as modules. Every application built in Angular must have at least one module. The module loaded first when the application is loaded is called a root module.

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

The platformBrowserDynamic loads the root module by invoking the bootstrapModule and giving it the reference to our Root module i.e AppModule

Root Module

The angular bootstrapper loads our root module AppModule. The AppModule is located under the folder src/app. The code of our Root module is shown below.

                              

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
 
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 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. Hence we import it.

                              

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

We use @NgModule class decorator to define an Angular Module and provide metadata about the Modules.

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

The @NgModule 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 components, directives, & pipes that belong to this Angular Module. We have only one component in our application. AppComponent.

Providers

The providers array is where we register the services we create. The Angular dependency injection framework injects these services in components and directives. pipes and other services.

Bootstrap

The component that angular should load when this Angular Module loads. The component must be part of this module. We want AppComponent load when AppModule loads, hence we list it here.

The Angular reads the bootstrap metadata and loads the AppComponent

AppComponent

Finally, we arrived at AppComponent, which is the root component of the AppModule. The code of 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 Class AppComponent is decorated with @Component Class Decorator.

The @Component class decorator provides the metadata about the class to Angular. It has 3 properties in the above code. Selector, templateURL & styleUrls

templateURL

This property contains an HTML template, which will be displayed in the browser. The template file is app.component.html

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

Template

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

We already have the app-root CSS selector defined in the index.html.

                              

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

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

Summary

We use ng build to build the application. The Angular compiler uses the angular.json to find the locations of application entry points (main.ts) & index.html. The compiler copies the code to the dist folder.

index.html loads the angular and third-party libraries.

We declare the root module in main.ts. Hence it will load next.

The root module declares its app.component.ts as its root component. Hence app.component loads next.

app.component.ts declares app.component.html as its template and app-root as its selector. Hence the template is loaded and displayed to the user.