Thursday, 26 April 2018

Angular Introduction to modules

Angular apps are modular and Angular has its own modularity system called NgModules. An NgModule is a container for a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities. It can contain components, service providers, and other code files whose scope is defined by the containing NgModule. It can import functionality that is exported from other NgModules, and export selected functionality for use by other NgModules.
Every Angular app has at least one NgModule class, the root module, which is conventionally named AppModule and resides in a file named app.module.ts. You launch your app by bootstrapping the root NgModule.
While a small application might have only one NgModule, most apps have many more feature modules. The rootNgModule for an app is so named because it can include child NgModules in a hierarchy of any depth.

NgModule metadata:
An NgModule is defined as a class decorated with @NgModule. The @NgModule decorator is a function that takes a single metadata object, whose properties describe the module. The most important properties are as follows.
  • declarations—The componentsdirectives, and pipes that belong to this NgModule.
  • exports—The subset of declarations that should be visible and usable in the component templates of other NgModules.
  • imports—Other modules whose exported classes are needed by component templates declared in this NgModule.
  • providers—Creators of services that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (You can also specify providers at the component level, which is often preferred.)
  • bootstrap—The main application view, called the root component, which hosts all other app views. Only the root NgModule should set this bootstrap property.
Here's a simple root NgModule definition:
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
  imports:      [ BrowserModule ],
  providers:    [ Logger ],
  declarations: [ AppComponent ],
  exports:      [ AppComponent ],
  bootstrap:    [ AppComponent ]
export class AppModule { }
The export of AppComponent is just to show how to export; it isn't actually necessary in this example. A root NgModule has no reason to export anything because other modules don't need to import the root NgModule.

NgModules and components:
NgModules provide a compilation context for their components. A root NgModule always has a root component that is created during bootstrap, but any NgModule can include any number of additional components, which can be loaded through the router or created through the template. The components that belong to an NgModule share a compilation context.
A component and its template together define a view. A component can contain a view hierarchy, which allows you to define arbitrarily complex areas of the screen that can be created, modified, and destroyed as a unit. A view hierarchy can mix views defined in components that belong to different NgModules. This is often the case, especially for UI libraries.

When you create a component, it is associated directly with a single view, called the host view. The host view can be the root of a view hierarchy, which can contain embedded views, which are in turn the host views of other components. Those components can be in the same NgModule, or can be imported from other NgModules. Views in the tree can be nested to any depth.
The hierarchical structure of views is a key factor in the way Angular detects and responds to changes in the DOM and app data.

NgModules and JavaScript modules:
The NgModule system is different from and unrelated to the JavaScript (ES2015) module system for managing collections of JavaScript objects. These are two different and complementary module systems. You can use them both to write your apps.
In JavaScript each file is a module and all objects defined in the file belong to that module. The module declares some objects to be public by marking them with the export key word. Other JavaScript modules use import statements to access public objects from other modules.
import { NgModule }     from '@angular/core';
import { AppComponent } from './app.component';

export class AppModule { }

Angular libraries:

Angular ships as a collection of JavaScript modules. You can think of them as library modules. Each Angular library name begins with the @angular prefix. Install them with the npm package manager and import parts of them with JavaScript import statements.
For example, import Angular's Component decorator from the @angular/core library like this:

import { Component } from '@angular/core';
You also import NgModules from Angular libraries using JavaScript import statements:
import { BrowserModule } from '@angular/platform-browser';
In the example of the simple root module above, the application module needs material from within the BrowserModule. To access that material, add it to the @NgModule metadata imports like this.
imports:      [ BrowserModule ],
In this way you're using both the Angular and JavaScript module systems together. Although it's easy to confuse the two systems, which share the common vocabulary of "imports" and "exports", you will become familiar with the different contexts in which they are used.

Tuesday, 24 April 2018

Angular Architecture Overview

Angular is a platform and framework for building client applications in HTML and TypeScript. Angular is itself written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps.
The basic building blocks of an Angular application are NgModules, which provide a compilation context for components. NgModules collect related code into functional sets; an Angular app is defined by a set of NgModules. An app always has at least a root module that enables bootstrapping, and typically has many more feature modules.
  • Components define views, which are sets of screen elements that Angular can choose among and modify according to your program logic and data. Every app has at least a root component.
  • Components use services, which provide specific functionality not directly related to views. Service providers can be injected into components as dependencies, making your code modular, reusable, and efficient.
Both components and services are simply classes, with decorators that mark their type and provide metadata that tells Angular how to use them.
  • The metadata for a component class associates it with a template that defines a view. A template combines ordinary HTML with Angular directives and binding markup that allow Angular to modify the HTML before rendering it for display.
  • The metadata for a service class provides the information Angular needs to make it available to components through Dependency Injection (DI).
An app's components typically define many views, arranged hierarchically. Angular provides the Router service to help you define navigation paths among views. The router provides sophisticated in-browser navigational capabilities.

Angular defines the NgModule, which differs from and complements the JavaScript (ES2015) module. An NgModule declares a compilation context for a set of components that is dedicated to an application domain, a workflow, or a closely related set of capabilities. An NgModule can associate its components with related code, such as services, to form functional units.
Every Angular app has a root module, conventionally named AppModule, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules.
Like JavaScript modules, NgModules can import functionality from other NgModules, and allow their own functionality to be exported and used by other NgModules. For example, to use the router service in your app, you import the Router NgModule.
Organizing your code into distinct functional modules helps in managing development of complex applications, and in designing for reusability. In addition, this technique lets you take advantage of lazy-loading—that is, loading modules on demand—in order to minimize the amount of code that needs to be loaded at startup.

Every Angular application has at least one component, the root component that connects a component hierarchy with the page DOM. Each component defines a class that contains application data & logic, and is associated with an HTML template that defines a view to be displayed in a target environment.
The @Component decorator identifies the class immediately below it as a component, and provides the template and related component-specific metadata.

Templates, directives, and data binding:
A template combines HTML with Angular markup that can modify the HTML elements before they are displayed. Template directives provide program logic, and binding markup connects your application data and the document object model (DOM).
  • Event binding lets your app respond to user input in the target environment by updating your application data.
  • Property binding lets you interpolate values that are computed from your application data into the HTML.
Before a view is displayed, Angular evaluates the directives and resolves the binding syntax in the template to modify the HTML elements and the DOM, according to your program data and logic. Angular supports two-way data binding, meaning that changes in the DOM, such as user choices, can also be reflected back into your program data.
Your templates can also use pipes to improve the user experience by transforming values for display. Use pipes to display, for example, dates and currency values in a way appropriate to the user's locale. Angular provides predefined pipes for common transformations, and you can also define your own.

Services and dependency injection:
For data or logic that is not associated with a specific view, and that you want to share across components, you create a service class.
A service class definition is immediately preceded by the @Injectable decorator. The decorator provides the metadata that allows your service to be injected into client components as a dependency.
Dependency injection (or DI) lets you keep your component classes lean and efficient. They don't fetch data from the server, validate user input, or log directly to the console; they delegate such tasks to services.

The Angular Router NgModule provides a service that lets you define a navigation path among the different application states and view hierarchies in your app. It is modeled on the familiar browser navigation conventions:
  • Enter a URL in the address bar and the browser navigates to a corresponding page.
  • Click links on the page and the browser navigates to a new page.
  • Click the browser's back and forward buttons and the browser navigates backward and forward through the history of pages you've seen.
The router maps URL-like paths to views instead of pages. When a user performs an action, such as clicking a link, that would load a new page in the browser, the router intercepts the browser's behavior, and shows or hides view hierarchies.
If the router determines that the current application state requires particular functionality, and the module that defines it has not been loaded, the router can lazy-load the module on demand.
The router interprets a link URL according to your app's view navigation rules and data state. You can navigate to new views when the user clicks a button, selects from a drop box, or in response to some other stimulus from any source. The Router logs activity in the browser's history journal, so the back and forward buttons work as well.
To define navigation rules, you associate navigation paths with your components. A path uses a URL-like syntax that integrates your program data, in much the same way that template syntax integrates your views with your program data. You can then apply program logic to choose which views to show or to hide, in response to user input and your own access rules.

You've learned the basics about the main building blocks of an Angular application. The following diagram shows how these basic pieces are related.

  • Together, a component and template define an Angular view.
    • A decorator on a component class adds the metadata, including a pointer to the associated template.
    • Directives and binding markup in a component's template modify views based on program data and logic.
  • The dependency injector provides services to a component, such as the router service that lets you define navigation among views.

Monday, 23 April 2018

Angular 5 Features

Angular 5 pent named as "pentagonal-donut" has the following 8 new features:
Optimized build:
In Angular 5, production builds created with the Angular CLI will now apply to the build optimizer by default. The build optimizer removes Angular decorators from your app's runtime codes thereby reducing the size of your bundle and increasing the boot speed of your application.
In addition, the build optimizer removes part of your application that is not needed during runtime via tree-shaking. This action leads to a decreased bundle size and faster application speed.

Server transfer State module:
If you have a screen with country master dropdown, state master dropdown, we end up with multiple HTTP calls from client to the server. Server transfer state generates information as part server side, and then transfers it to the client side so that this information does not need to be regenerated.
The Angular Universal team has added Domino to the platform-server. This simply means more DOM manipulations can happen out of the box within server-side contexts.
Furthermore, two modules, ServerTransferStateModule and BrowserTransferModule have been added to Angular Universal. These modules allow you to generate information as part of your rendering with platform-server and then transfer it to the client side to avoid regeneration of the same information. In summary, it transfers state from the server which means developers do not need to make a second HTTP request once the application makes it to the client.

Incremental builds:
In the previous versions of Angular every time we do a build it builds from scratch, you either change or do no change the code. From Angular 5 it will use typescript transform which was introduced in Typescript 2.3. This will ensure speedy builds of the project.

Removing White spaces:
Previously white spaces, tabs and so on where part of build output. That can now be removed from the project final build output by providing "preserveWhitespaces" as true in the tsconfig.json file as shown in the below code.
{        ...
  "angularCompilerOptions": {
    "preserveWhitespaces": false
  "exclude": [

Router Life cycle events:
Routing is one of the important part of Angular to create SPA application. In routing we have something called as Route guards. In Angular 5 they have defined routing life cycle which helps to track when router moves from guards to completion state.
The routing life cycle events fire in the following sequence:
  • GuardsCheckStart
  • ChildActivationStart
  • ActivationStart
  • GuardsCheckEnd
  • ResolveStart
  • ResolveEnd
  • ActivationEnd
  • ChildActivationEnd

Export alias support:
Components and directives can now have multiple names. So when you have code changes internally you can expose with new names without breaking the existing code.
import { Component } from '@angular/core';
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  exportAs:'dashboard, logBoard'
export class AppComponent {
  title = 'app';

Lambdas in providers (Improved Decorator Support):
Angular 5 now supports expression lowering in decorators for lambdas, and the value of useValue, useFactory, and data in object literals. Furthermore, a lambda can be used instead of a named function like so:
In Angular 5:
    provider: [{provide: 'token', useFactory: () => null}]
  export class MyClass {}
Before Angular 5:
    provider: [{provide: 'token', useValue: calculated()}]
  export class MyClass {}

Forms Validation in Angular 5 (Blur and submit events):
In Angular 5, forms now have the ability to decide when the validity and value of a field or form are updated via on blur or on submit, instead of every input event.
Example Usage:
<input name="nickName" ngModel [ngModelOptions]="{updateOn: 'blur'}">
Another Example: 
<form [ngFormOptions]="{updateOn: 'submit'}">
In the case of Reactive forms, you can add the option like so:
ngOnInit() {
  this.newUserForm ={
    userName: ['Bob', { updateOn: 'blur', validators: [Validators.required] }]

Internationalized Number, Date, and Currency Pipes:
Angular 5 ships with new number, date, and currency pipes that increase standardization across browsers and eliminate the need for i18n polyfills. The pipes rely on the CLDR to provide extensive locale support and configurations for any locales you want to support. To use the old pipes, you will have to import the DeprecatedI18NPipesModule after the CommonModule.
 import { NgModule } from '@angular/core';
  import { CommonModule, DeprecatedI18NPipesModule } from '@angular/common';
    imports: [
      // import deprecated module after
  export class AppModule { }

Faster Compiler in Angular 5:
A lot of improvements have been made to the Angular compiler to make it faster. The Angular compiler now leverages TypeScript transforms. You can take advantage of it by running:
ng serve --aot was used as a case study and the compiler pipeline saved 95% of the build time when an incremental AOT build was performed on it.
Note: TypeScript transforms are a new feature introduced as part of TypeScript 2.3, that allows hooking into the standard TypeScript compilation pipeline.