Krishan Dutt Sharma

Web Developer

Topics

Angular application get start?

An Angular application gets loaded or started by the following ways.
  • First Main.ts will load and execute method:
platformBrowerDynamic().bootstraoModule(AppModule).catch(err => console.log(err));
Here, AppModule is our application module which is registered here.
  • App.module.ts : In app.module.ts we registered our default component with is loaded other component.
  • App.component.ts :  Now we create our first component called app.component.ts here, two other files also created with app component called app.compoenent.html and app.component.css and both file are registered in @component directive like below:
@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrl:['./app.component.css']
}) 
  • index.html: Now add app component on index.html page like below:
<body>
<app-root>Loading....</app-root>
</body>
  • app.component.html: Here we add our html component which is loaded on index.html page.
Note: If we want to change the default component name in our application then we change it in app.Module.ts and if you want to change the default module file name the it will the change in main.ts file.

Angular Library

You can create and publish libraries to extend the angular functionality.A simple example might be a button that send the user to your website, that would be include in all application of your company.

Let's create Angular Library,

ng new my-workspace --create-application=false

cd my-workspace ng generate library

my-lib


This creates the projects/my-lib folder in your workspace, which contains a component and a service inside an NgModule. The workspace configuration file, angular.json, is updated with a project of type 'library'.

"projects": {

  ...

  "my-lib": {

    "root": "projects/my-lib",

    "sourceRoot": "projects/my-lib/src",

    "projectType": "library",

    "prefix": "lib",

    "architect": {

      "build": {

        "builder": "@angular-devkit/build-ng-packagr:build",

        ...

You can build, test, and lint the project with CLI commands:
ng build my-lib
ng test my-lib
ng lint my-lib

Why we need Angular?

As explained above, Angular is completely rewritten, now you need to know why we are using Angular while we have AngularJS. So, the answer is Angular is designed by the team for all the devices. With AngularJS, a developer got problem when using the application on mobile or any other device except web. Thus, the team decided they will develop Angular which can be used for all the devices, as Mobile, iPhones, Tablets etc.
It's the product of Google so every developer wants to learn Angular nowadays. There are a few main things one should know.
  • Easier: Angular is easier to learn; within a limited time, we can learn it and create the applications with sample CRUD feature.
  • Performance: Its performance is way better as compared to AngularJS because the execution is very fast when we perform any operation in the application.
  • TypeScript: Nowadays, most of the developers are using TypeScript because it's easier to learn since it is based on OOPS concepts and is a superset of JavaScript. As you know, most of the developers have knowledge of OOPS, so they can learn it in a minimal time.
  • Angular Testing Easy: When we work on an Angular project, we can easily test the application by creating the test cases and it's easier than others.
  • Increased Developer Productivity: Angular increases the developer productivity because a developer can easily learn and complete any task or feature quickly.
  • Work in Coding pattern: With the help of Angular, you can work on a good consistent coding pattern because it provides codelyzer by which you can write consistent code and discover potential errors.
  • Angular uses full featured Routing: Routing is yet another great feature of Angular. Angular performs navigation from one view to another and works very fast. It supports lazy loading that allows you to load the pieces of code on demand means entire code will not run one time.
  • Easily build and use only required file: When we build the Angular v2 - v6 application, the application will build and required file will store in a dist file. In the dist folder, only necessary files will be saved.
  • Change detection: It's a very important feature of Angular. It refreshes the running application whenever the changes in code are made.

Angular File Structure

The structure of the Angular 7 app on WebStorm IDE (how it looks on IDE). For Angular 7 development, you can use either Visual Studio Code IDE or WebStorm IDE. Both are good. Here, we are using JetBrains WebStorm IDE.

Angular 7 App Files Explanation

Files used in Angular 7 App folder

Angular 7 App files which are mainly used in your project are given below:

  • src folder: This is the folder which contains the main code files related to your angular application.
  • app folder: The app folder contains the files, you have created for app components.
  • app.component.css: This file contains the cascading style sheets code for your app component.
  • app.component.html: This file contains the html file related to app component. This is the template file which is used by angular to do the data binding.
  • app.component.spec.ts: This file is a unit testing file related to app component. This file is used along with other unit tests. It is run from Angular CLI by the command ng test.
  • app.component.ts: This is the most important typescript file which includes the view logic behind the component.
  • app.module.ts: This is also a typescript file which includes all the dependencies for the website. This file is used to define the needed modules to be imported, the components to be declared and the main component to be bootstrapped.

Other Important files

  • package.json: This is npm configuration file. It includes details about your website's package dependencies along with details about your own website being a package itself.
  • package-lock.json : This is an auto-generated and modified file that gets updated whenever npm does an operation related to node_modules or package.json
  • angular.json: It is very important configuration file related to your angular application. It defines the structure of your app and includes any settings associated with your application. Here, you can specify environments on this file (development, production). This is the file where we add Bootstrap file to work with Angular 7.
  • .gitignore: This file is related to the source control git.
  • .editorconfig: This is a simple file which is used to maintain consistency in code editors to organize some basics such as indentation and whitespaces.
  • assets folder: This folder is a placeholder for resource files which are used in the application such as images, locales, translations etc.
  • environments folder: The environments folder is used to hold the environment configuration constants that help when building the angular application. The constants are defined in 2 separate .ts files (environment.ts and environment.prod.ts), where these constants are used within the angular.json file by the Angular CLI. For example, if you run the ng build command, it will build the application using the development environment settings, whereas the command ng build ?prod will build the project using the production environment settings.
  • browserlist: This file is used by autoprefixer that adjusts the CSS to support a list of defined browsers.
  • favicon.ico: This file specifies a small icon that appears next to the browser tab of a website.
  • index.html: This is the entry file which holds the high level container for the angular application.
  • karma.config.js: This file specifies the config file for the Karma Test Runner, Karma has been developed by the AngularJS team which can run tests for both AngularJS and Angular 2+
  • main.ts: As defined in angular.json file, this is the main ts file that will first run. This file bootstraps (starts) the AppModule from app.module.ts , and it can be used to define global configurations.
  • polyfills.ts: This file is a set of code that can be used to provide compatibility support for older browsers. Angular 7 code is written mainly in ES6+ language specifications which is getting more adopted in front-end development, so since not all browsers support the full ES6+ specifications, pollyfills can be used to cover whatever feature missing from a given browser.
  • styles.css:/ This is a global css file which is used by the angular application.
  • tests.ts: This is the main test file that the Angular CLI command ng test will use to traverse all the unit tests within the application and run them.
  • tsconfig.json: This is a typescript compiler configuration file.
  • tsconfig.app.json: This is used to override the tsconfig.json file with app specific configurations.
  • tsconfig.spec.json: This overrides the tsconfig.json file with app specific unit test configurations.

What is AOT in angular?

The Angular ahead-of-time (AOT) compiler converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and runs that code. Compiling your application during the build process provides a faster rendering in the browser.

This guide explains how to specify metadata and apply available compiler options to compile your applications efficiently using the AOT compiler.

Here are some reasons you might want to use AOT.

  • Faster rendering With AOT, the browser downloads a pre-compiled version of the application. The browser loads executable code so it can render the application immediately, without waiting to compile the app first.
  • Fewer asynchronous requests The compiler inlines external HTML templates and CSS style sheets within the application JavaScript, eliminating separate ajax requests for those source files.
  • Smaller Angular framework download size There's no need to download the Angular compiler if the app is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload.
  • Detect template errors earlier The AOT compiler detects and reports template binding errors during the build step before users can see them.
  • Better security AOT compiles HTML templates and components into JavaScript files long before they are served to the client. With no templates to read and no risky client-side HTML or JavaScript evaluation, there are fewer opportunities for injection attacks.

For AOT compilation, need to Add --aot flag in command. i.e, ng build --aot.


Angular has two built-in compilation strategies:

1. JIT ( Just in time)

2. AOT ( Ahead of time) 

In JIT we need to download the Angular compiler into the client browser, which converts the Angular code into browser understandable JavaScript.

Angular compiler size is around 2 MB which requires some time for the browser to download into client machine. Whereas in AOT we do not require Angular compiler.

During AOT step only code is converted into browser understandable JavaScript. ng build --prod will internally make use of AOT compilation. Using AOT and Lazy loading module we can reduce the page rendering time in Angular.

What is New In Angular 8.0

New Features of Angular 9.

Now, it’s time to discuss the major changes made in Angular 9.

TypeScript 3.4.x Support

 
Angular 8 supports the TypeScript 3.4 or above version. So, if we want to use Angular 8 for our application, then we need to first upgrade the TypeScript to 3.4 or above.

Ivy Rendering Engine

Angular Ivy is the new rendering architecture that comes, by default, with version Angular 9.Currently, Angular 8 uses as rendering architecture called View Engine. The Ivy project is rewriting the Angular compiler and run-time code to make it better, faster, and smaller.

Components of Ivy:
       1.Tree shakable:

Angular Ivy is a next-generation compilation and rendering pipeline, which reduces the bundle size, loads faster in slower networks and is simple to use.

Bazel Support:

Bazel allows us to break an application into distinct build units. In Angular, build units are defined at the NgModule level. Brazel helps in incremental build.We can achieve the below benefits by using this tool,
  1. It will provide a faster build time. It will normally take time for the first build but taking less time from the concurrent builds.
  2. Using this tool, we can able to build the application as an incremental build and deploy only what has been changed rather than the entire app.
  3. We can eject the Bazel file which is normally hidden.
We can add Bazel Support using the below Angular CLI Command.

Differential Loading for Performance Optimization:

It is one of the cool new features in the Angular CLI 8. Because with the help of these features, we will specify which browser we will target and the CLI will build the application with related necessary JS bundles with the necessary polyfills. The default target browser in the tsconfig.json file is now es2015. It means when CLI build the application, it will build for the modern browser which supports ES6 features. But, we need to run the application in an older browser like IE9, then we need to specify it in the browserlist file. This file actually exists in the root folder of the CLI project and previously, it is used for the CSS part only. Now, it can be used for JS generation.

Changes in Lazy Loading in Route:

In Angular from the beginning, the router mechanism always supports the concept of lazy loading. Till Angular 7, it was done by the string value of the loading module as below,
  1. {  
  2.    path: 'lazy',  
  3.    loadChildren: () => './admin/admin.module#AdminModule'  
  4. }  
The value up to the #(hash) sign represents the path of the module file in which the target component exists and the value after the hash sign represents the class name of that module. This style will still work in Angular 8. But the way of writing lazy module has been changed. The string value of the loadchildren has been deprecated due to the support of ECMAScript and Ivy will only support this. So, now the loadchildren declaration will be like this,
  1. {  
  2.    path: 'lazy',  
  3.    loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)  
  4. }  

Web Worker Support:

As we all know that JavaScript is always executes in a single-threaded manner. So, it is important to perform any huge data call or any consecutive Rest API call in an asynchronous manner. But, in a real application based scenario, this concept will not help us. That’s why today all the web browsers support the web worker process. Basically, the web worker process is the scripts executed by the browser in a separate thread. Communicate with that thread in the browser tab will be done by sending messages. So, in general, web worker is not related to Angular from any point-of-view. But, the main point is that these scripts need to be considered in the build process of the application. So, that after deployment of application the same process can be performed continuously. So, the main objective is to provide one single bundle for every web worker. Now, in Angular 8 this task can be performed by the Angular CLI.

Also, we can configure our Angular CLI project if we add the web worker for the first time. In this process, CLI will exclude the worker.ts files from the tsconfig.json files and also, add a new TypeScript configuration file named tsconfig.worker.json which handles the worker.ts file. Also, this information also added to the angular.json file as
  1. "webWorkerTsConfig""tsconfig.worker.json" 

What is Bazel?

Between new features and unit tests, developers add several new files to their projects every sprint.

Before you know it the application is huge! Builds end up taking several seconds, sometimes in the double digits for very large projects.

This is a scalability problem we see with most build pipelines. In this article we will discuss how to improve build performance by adding Bazel to the toolchain.

Disclaimer: Bazel with Angular is still considered experimental by the Angular team. It’s not recommended to use it for production yet. Some of the things that are still being worked on include better Windows support and integration with a dev server.

Bazel

Since source code changes often happen in small increments, it doesn’t make sense to rebuild the entire application for every little change. Instead we should only rebuild code that actually changed, and code that depends on the changes.

Bazel allows us to break an application into distinct build units. In Angular, build units are defined at the NgModule level.

This means the scope of a build can be as granular as a single NgModule. If a change is internal to an NgModule, only that module needs to be rebuilt.

Of course, if we change the public api of something in the NgModule, any NgModule with a reference to it will be have to be rebuilt as well.

In any event, the time to build the application is greatly reduced since we are churning through a lot less code per build.

Bazel Application

The structure of the application is very similar to applications generated by Nx. We don’t support Bazel in Angular CLI or Nx yet, but are working with the Angular team to have support soon.

Nx (Nrwl Extensions for Angular) is an open source toolkit for enterprise Angular applications.

One of the main goals of Nx is to make it easier to build large mono repo applications.

We expect Bazel to play an important role in this to ensure fast builds.

The sample application consists of two parts:

A luxury car application under the apps folder, and a cars library under the libs folder.

The application relies on LuxuryCarService from the cars library to load cars.

What is bootstrapping in Angular?

In this article on Bootstrapping in Angular, let us find out how Angular works internally and bootstraps our app. We use ng new to create a new Angular project. It generates lots of boilerplate codes. It also configures the Typescript, Webpack, Karma, & Protractor. 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.

What is a Bootstrapping

Bootstrapping is a technique of initializing or loading our Angular application.

let’s walk through our 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!”. The Angular takes the following steps to load our first view.

  1. Index.html loads
  2. Angular, Third-party libraries & Application loads
  3. Main.ts the application entry point
  4. Root Module
  5. Root Component
  6. Template

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. Neither you can see a stylesheet file. The body of the files has the following HTML tag.

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 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

Use ng build --prod to build and distribute the app for production. For testing/debugging use ng build. The production build optimizes, minimize and uglify the code.

Now open the dist and open the index.html.

You can see that the compiler included five script files. They are runtimepolyfillsstylesvendor, & main. All these files have two versions one is es5 & the other one es2015

Since the Angular 7we have new feature called conditional polyfill loading. Now Angular builds two script files, one for es2015 & another for es5. The es2015 (es6) is for modern browser and es5 is older browsers, which do not support the new features of es2015.

Note the nomodule attribute, which tells the modern browser to ignore the script and do not load it. Hence es5 scripts are not loaded in the modern browsers

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 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 Angular Version 2 generated only three script files ( inline.js, styles.bundle.js & main.bundle.js).

These files are added by the Webpack module loader.

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 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.Application Loads

So when index.html is loaded, the Angular core libraries, 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 of the angular.json is shown below

The angular-cli.json was the configuration file in Angular 5 and before. It is now angular.json since the version Angular 6.

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

The main.ts file is as shown below.

Let us look at the relevant code in detail.

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

What is platformBrowserDynamic

platformBrowserDynamic is the module, which is responsible for loading the Angular application in the desktop browser.

The 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 from nativescript-angular/platform library and will be calling platformNativeScriptDynamic().bootstrapModule(AppModule). Read more about Angular Nativescript bootstrap process from here

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, which is loaded first when the application is loaded is called a root module.

TheplatformBrowserDynamic 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

The root module must have at least one root component. The root component is loaded, when the module is loaded by the Angular.

In our example, AppComponent is our root component. Hence we import it.

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

The @NgModule has several metadata properties.

imports

We need to list all the external modules required including other Angular modules, that is used by this Angular Module

Declarations

The Declarations array contains the list of components, directives, pipes & Services that belong to this Angular Module. We have only one component in our application AppComponent.

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

Component

Finally, we arrive at AppComponent, which is the root component of the AppModule. The code of our AppComponent is shown below

The Class AppComponent is decorated with @Component Class Decorator.

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

templateURL

This property contains an HTML template, which is going to 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.htmland the CSS Selector is app-root

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

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