Tuesday, October 30, 2018

Eager, Lazy and Preloading modules in Angular

In the previous posts we have seen about Feature modules which are added to the root module for better modularity and maintainability of the Angular applications. Depending on the need there are 3 different ways in which modules can be loaded in an Angular application.

Eager loading
Laze loading &
Preloading

Saturday, October 27, 2018

Types of Feature Modules

Feature Modules are additional modules which can be added to the root module for better modularity and maintainability of the Angular applications. Feature modules also help improving the performance of larger applications using lazy loading where only the root module is loaded initially other modules are loaded on demand thereby improving performance.

There are 6 different types of feature modules in Angular, they are.

Thursday, October 25, 2018

Feature Modules in Angular

Feature Modules are additional modules which can be added to the root module for better modularity and maintainability of the Angular applications. As the application grows it becomes difficult to maintain all the components, services etc in a single root module, hence we organize the components into sub-modules called Feature Modules and hook them to the root module.

The feature modules should be included in the imports[] section of the root module so that they can be loaded when required. Once we add the feature modules in the import list, we render the components in the feature module in the root modules components by embedding the feature module component’s selector tags anywhere in the root modules components.

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


<!-- Main comonent template -->
<app-feature-component></app-feature-component>

Feature Module example in Angular

Feature Modules are additional modules which can be added to the root module for better modularity and maintainability of the Angular applications. As the application grows it becomes difficult to maintain all the components, services etc in a single root module, hence we organize the components into sub-modules called Feature Modules and hook them to the root module.

In this example let us see how to create a FeatureModule, import it in the root module and render the contents of the FeatureModule components in the root modules components.

What are Angular Modules


In Angular Modules are the one which combine the various units like components, service, directives etc into a full application. Every Angular application should have at least one Module called the root module which binds the units together and bootstraps the application. Larger applications can have additional modules for better modularity and maintainability.

Angular modules are classes decorated with the @NgModule decorator. The following are some of the important properties declared while creating an Angular Module.

Tuesday, October 23, 2018

Two way binding in Angular

Two way binding is nothing but the ngModel which we used in AngularJS. As the name indicates two-way binding binds changes in the view to the model and any changes in the model to the view.

Two way binding is represented with a combination of square and curly braces in Angular [(ngModel)]. The property to be bound follows the [()] symbol as follows.

[(ngModel)] = 'productName'

Let us understand two way binding with a simple example, we have a textbox in the view whose value is bound using two-way binding to a property in the component myValue. When the component initializes the value set in the component class will get displayed in the textbox, and when the user changes the value in the textbox the change is reflected in the model, we will show this by displaying the value of property myValue in a label using interpolation.

Monday, October 22, 2018

Event Binding in Angular

Event binding is one-way binding in Angular from the view to the component class. 
Event binding is used to handle events which arise out of the controls in the view, like button click event, textbox blur event etc. 
Event binding in Angular is represented using a set of braces (). The event to be triggered is placed inside the braces like (click), and the handling function comes after the = sign, as follows. 
(click)="clickHandler()"

Let us understand event binding with a simple example, we have a button in the view whose click event is bound to the handler function clickHandler(), in the hander function we set the property clickMessage which will get displayed in the view as interpolation.

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() { }
  clickMessage ='';
  clickHandler() {
    this.clickMessage = 'You clicked the Button.';
  }
}
app.component.html
<div<
  <input type="button" (click)='clickHandler()' value="Click Me"<
  {{clickMessage}}
</div<

In the view we tie the buttons click event with the event handler function clickHandler. In the event handler function we set the clickMessage property, and this gets displayed in the view as an interpolation. The output is as follows. 




Sunday, October 21, 2018

Property Binding in Angular

Property binding is one-way binding in Angular from the component class to the view template. Property binding is similar to interpolations but there are few differences in the way we bind them to the view.

Property binding is mostly used to assign values to HTML tags, for example we can use property binding to assign the source URL of an image tag, assign values to a textbox etc. Property binding is used in places where we can directly assign the property without any manipulations, interpolations are used in places where we need to append the property values with other text in the template.

Let us understand property binding with a very simple example, we will set a property title in the component and assign it as value to a textbox in the view.

Interpolation in Angular

Interpolation is the simplest form of data binding in Angular, Interpolation is one-way data binding from the Component class to the view template. Interpolation is implemented using a double set of curly braces enclosing a property which is defined in the component.

{{property}}

At runtime Angular gets the value of the property from the component and displays it in the view.  Interpolation can be used to display text/messages in the view. Interpolation comes in handy when we need to append components property values with other text in the view.

Let us understand Interpolation with a very simple example, we will set a property title in the component and display it in the View using interpolation.

Friday, October 19, 2018

Types of Binding in Angular

Binding is used to bind the model properties and controller functions to the View. Let us now see the different types of bindings offered by Angular.

Angular provides 4 different types of binding.

1. Interpolations
2. Property Binding
3. Event Binding
4. Two way binding

What is Biding in Angular?

Binding is the concept by which the properties and functions in the model/controller are bound to the View. Remember that Angular is a client side MVC architecture.

In AngularJS the $scope was the model which contains the model properties and the controller had the function. Views are HTML files or other files like the MVC view files (.cshtml). Both the model properties and the controller functions are bound to the view using Binding.

In Angular the Component class contains the model properties and functions and the template .html files represent the View. The model properties and functions are bound to the view template file using Binding. 

Thursday, October 11, 2018

Output property example in Angular 6

Output properties are outbound properties which flows from a child component to its parent component. These are events which originate from the child component and get handled in the parent component.

In this example we shall see on how to declare a @Output property in a child component and how to pass an event through the @output property to the parent component and handle the event in the parent component.

Let us start with the Input component example and extent it by adding a @Output property to it.

Output properties in Angular

Output properties are outbound properties which flows from a child component to its parent component. These are events which originate from the child component and get handled in the parent component.

Output properties are marked with the @Output decorator and returns an Angular EventEmitter.
Output properties are declared using the @Output decorator as follows.

Input property example in Angular 6

Input properties are inbound properties which flows into a component from a parent component. Input properties are setter properties marked with the @Input decorator.

In this example we shall see on how to declare a @Input property in a child component and how to pass value to it from the parent component. We will get the value of the @Input property and display it in the child components view template.

Input properties in Angular

As the name implies @Input properties are inbound properties which flows into a component from a parent component. Input properties are setter properties marked with the @Input decorator.

Input properties are declared using the @Input decorator as follows.

@Input() Message: string

Once the property is declared in a component, we can pass values to the component from the parent component along with the component’s selector tag as follows.



Here parentMsg is a property defined in the parent component whose value gets passed to the child component through the Message @Input property.

Child component example in Angular 6

Angular applications are built with a set of components often nested set of components. We can embed a component inside another component using the nested components selector tag. Let us create a very basic child component and embed it in the home component.

Let us start with creating a child component using the following command

ng g c child

The command will create a component class file child.component.ts and a template file child.component.html. In this example we will not make any changes to the class file, we will add a simple message to the template file.

Wednesday, October 10, 2018

Route Guard example in Angular 6


Let us extent our Angular Routs example and add some route guards to the example. Let us add the most basic route guard CanActivate to the example. Let us begin by adding 2 services auth service and a route-guard service as follows.

ng g s auth
ng g s route-guard

Angular Route Guards

Route Guards are special validation checks which can be used to validate requests to load specific routes/modules, we can validate the request and either accept or deny the request to load the route. Route guards return a true/false value which decides where the user can access the route or not.

There are 5 route guards

Tuesday, October 9, 2018

Routing example in Angular 6

Routing in Angular is a feature which helps us to load different components in the UI based on user actions like clicking a link etc. Apart from clicking on the links we can also change the URL in the browser and view the components mapped to the various routes.

Let us start with a basic Routing example, let us begin by creating a new component routeApp by running the ng generate component command as follows.

ng generate component routeApp

Monday, October 8, 2018

Observable example in Angular 6

An Observable is a way to execute asynchronous operations, in Angular Observable is supported using the RxJs library. An Observable makes an asynchronous request and returns the success response or an error if the request fails. The most common usage of observable is to make API calls to services to get data. Let us see on how to make async calls using observable to get data and display it in UI using Angular.

The Angular HttpClient library by default gives an Observable, let us use the Observable to get API data and display the results in the Component UI.

Let us extend our previous Promise example, we will use the same userdata.service from the previous example and add an Observable to it. This way we can compare the Promise and Observable in the same example code.

Promise example in Angular 6

A Promise is a way to execute asynchronous operations. A Promise can give 2 possible results a success response or a failure error message. The most common usage of promises is to make API calls to services to get data. Let us see on how to make async calls using promises to get data and display it in UI using Angular.

The Angular HttpClient library by default gives an Observable, for the sake of this example we will convert the Observable to a Promise and use it in the Component to display the results from the API call.

Let us extend our previous Service example, let us start by adding a new service userdata.service using the ng generate command as follows.

Sunday, October 7, 2018

Service example in Angular 6

Services in Angular are classes which perform a specific / unit of work. Services with a well-defined purpose and help in modularizing the application design.

Components deal with the UI of the application, hence they delegate data specific operations like fetching data from server, validating data etc to Services. Since services are outside the component, they can be re-used by injecting into the required components, thereby enabling re-usability of shared service code.

To create a new service we need to use the ng generate cli command

ng generate service

In the following example we shall create a very simple service hello.service, which has a function getMessage(), the function just returns a string message. We shall use this service in a component and display the message returned by the service in the component UI.

Friday, October 5, 2018

HelloWorld example in Angular 6

Before we start with the Angular 6 example make sure that you have Node and npm installed in the PC. Npm gets installed along with Node, we can confirm this using the commands

node –v
npm –v

These commands will give the versions installed, once this is confirmed we can go to the next step.

Next install angular-cli, which is the command line interface for Angular, we will need Angular-Cli to create projects / components / services, launch Angular applications etc. Use the following npm command to install angular-cli.

npm install -g @angular/cli

Once angular-cli is install we can start creating the actual Angular project, to create the project type the following command in the folder where we want to create the Angular Project.

Tuesday, October 2, 2018

What's new in Angular 6


Angular 6 was released in May 2018. Angular 6 introduces Angular Elements, which gives us ability to use Angular components in other environments like jQuery. Using Angular Element and Angular Component can be wrapped in a DOM element and used in a HTML page.

Angular 6 introduces new Angular CLI commands ng add & ng update. ng add helps us to add new packages to the project and ng update helps update the dependent packages in the project. For example, the command ng update @angular/core will update all of the Angular framework packages as well as RxJS and TypeScript, and will run any schematics available on these packages to keep you up to date.

What's new in Angular 5

Angular 5 was released in November 2017. The focus of Angular 5 was to make Angular faster again. The loading time has been improved by smaller bundles. The execution has been improved as well by optimizations at the compiler. Build optimizer was a major feature introduces in Angular 5, the build optimizer helps clean up unwanted code and reduce the size of the compiled bundle. Angular 5 supports TypeScript 2.4.

Angular 5 added further enhancements to Angular Universal, added modules ServerTransferStateModule & BrowserTransferStateModule. This module allows you to generate information as part of your rendering with platform-server, and then transfer it to the client side so that this information does not need to be regenerated.

Added new lifecycle events to the router to track the cycle of the router from the start of running guards through to completion of activation. The new events are GuardsCheckStart, ChildActivationStart, ActivationStart, GuardsCheckEnd, ResolveStart, ResolveEnd, ActivationEnd, ChildActivationEnd.

What's new in Angular 4

Angular 4 was released in March 2017, version 3 was skipped due to internal issues with router packages. Angular 4 introduced Ahead of Time AoT compilation of templates, through which the templates a compiled at build time and converted to JavaScript.

AoT compilation has 2 advantages, compilation happens in the server during the build process, hence the client/browser has less load, also by compiling at build time we can capture errors in templates beforehand instead of breaking in the browser at run-time. Angular team also improved the View Engine, which helped in producing less code when you use the Ahead of Time compilation.
Angular 4 introduced a new package for animation - @angular/platform-browser/animations.
Angular 4 introduced some improvements to ngIf, ngFor directives, provides a new titlecase pipe, simplified http request format, improvements to Router and internationalization etc.

Angular v4.3 introduced the HttpClient in @angular/common/http which offers a simplified client HTTP API for Angular applications, this new module provides benefits like typed request and response objects, request and response interception, Observable apis, and streamlined error handling.

Angular version History


The Angular history stated with version 2 back in September 2016, the latest available version as of today is Angular 6. Let us briefly look at the release history and features added to each version of Angular.