Friday, November 30, 2018

Pure vs Impure pipes

Angular pipes execute based on changes detected to the input value to which the pipe is applied. Based on how the changes should be detected there are 2 types of pipes Pure and Impure pipes.

By default pipes are pure in Angular. Pure pipes get executed when there is a change to the input value to the pipe. These changes include changes to primitive types like String, Number, Boolean etc, and changes to object references i.e when assignment happens to object, arrays etc.

Note that pure pipes get triggered only when the reference of the object/array is changed. Pure pipes will not get triggered when we add an element to an existing array (or) when we update a property of an input object, but will get executed when the input array is assigned with a different array or when an input object is assigned with a different object. When we add an element to the existing array the reference remains the same hence the pipe will not get executed.

Impure pipes get executed for every change detected to the component like a key press, mouse move etc. Impure pipes get executed more often when compared to pure pipes. Hence impure pipes should be implemented with greater care.

In some cases pure pipes might not solve the need, for example if we want a pipe to get executed based on addition/removal of elements from an array, then a pure pipe will not work, in these cases we should develop an impure pipe.

Thursday, November 29, 2018

Angular Custom Pipes

In the previous posts we saw about the built-in pipes in Angular, their syntax, usage, chaining etc. Angular also provides us the ability to create our own custom pipes to suite our requirement. When we cannot use any of the built-in pipes for our requirement we can create a custom pipe. Also for larger applications, create custom pipes helps in reusing code/functionality.

Custom pipes are nothing but classes like Components and custom Directives, Custom pipe classes use the @Pipe decorator. The pipe class implements the PipeTransform interface's transform method that accepts an input value followed by optional parameters and returns the transformed value.

While creating the custom pipe class, use the @Pipe decorator and specify the name of the custom pipe as follows.

Angular chaining pipes

Chaining pipes is Angular nothing but arranging more than one pipe in sequence so that the input value gets transformed in stages through the various pipes chained together. The successive pipes in the chain should be separated by a pipe symbol.

{{<input value> | <pipe 1> | <pipe 2> | . . . | <pipe n>}}

While chaining pipes we can also specify parameters for any of the pipes in the chain, in which case the pipe and its parameter are separated by a colon (:) symbol. Parameters are optional, also we can selectively specify parameters for certain pipes in the chain and ignore for other pipes.

 {{<input value> | <pipe 1> : <parameter> | <pipe 2> | . . . | <pipe n> <parameter>}}

In the following example we will use a date pipe, followed by an uppercase pipe. The input value will be a date object which holds the current date.

Wednesday, November 28, 2018

Angular built-in pipes examples

Angular provides different types of built-in pipes like DatePipe, CurrencyPipe, Upper/Lower/Title case pipes etc. In this post we shall see examples of some of the commonly used built-in pipes.

DatePipe
DatePipe is used format date and time, it takes a Date object followed by a date pipe, followed by a formatting parameter which tells how the date should be formatted

<Date Object> | date : <format>

Following are some of the sample for DatePipe formatting.
Pipe
Output
{{ currentDate | date: 'short' }}
11/27/18, 11:56 PM
{{ currentDate | date: 'medium' }}
Nov 27, 2018, 11:58:42 PM
{{ currentDate | date: 'long' }}
November 27, 2018 at 11:58:08 PM GMT-5
{{ currentDate | date: 'shortDate' }}
11/28/18
{{ currentDate | date: 'mediumDate' }}
Nov 28, 2018
{{ currentDate | date: 'longDate' }}
November 28, 2018
{{ currentDate | date: 'shortTime' }}
12:02 AM
{{ currentDate | date: 'mediumTime' }}
12:02:05 AM
{{ currentDate | date: 'longTime' }}
12:02:05 AM GMT-5

CurrencyPipe
The CurrencyPipe transforms a number to a currency string, formatted according to locale rules that determine group sizing and separator, decimal-point character, and other locale-specific configurations.

CurrencyPipe takes a number as input, followed by the currency pipe and a parameter to specify the required format.

<number> | currency : <format parameters>

Following are some of the sample for CurrencyPipe formatting.
Pipe
Output
{{ 1500.45 | currency }}
$1,500.45
{{ 1500.45 | currency : 'USD' }}
$1,500.45
{{ 1500.45 | currency : 'USD' : 'symbol' }}
$1,500.45
{{ 1500.45 | currency : 'USD' : 'code' }}
USD1,500.45


Angular built-in pipes

Angular pipes provide us an important feature of formatting / transforming data to a desired way in the view.

For example date formatting is one common requirement which we need in all applications. Angular provide different Date Pipes like shortDate, longDate, fullTime etc which come in handy to display different formats of dates in the UI.

Angular Pipes

Pipes in Angular are used to format / transform data and display it in the UI. Pipes are not new in Angular, for those familiar with AngularJS can connect the same concept in Angular. The very basic pipe takes one input followed by the pipe | symbol which is again followed by the type of pipe to be used for transformation.

<input> | <pipe type>

Pipes can have additional parameters to add more formatting / specification on how the transformation should be done, parameters are followed by the pipe type with a colon : symbol

<input> | <pipe type> : <parameter>

Pipes can have multiple parameters chained in sequence, each parameter in the chain is separated with a colon : symbol

<input> | <pipe type> : <parameter1> : <parameter2> . . . : <parameterN>

Tuesday, November 27, 2018

Custom Structural Directive example

Structural directive in Angular manipulate the DOM by adding/removing a set of elements. Attribute directives on the other hand decorate the element with more content/features. Structural directives can be identified with the * mark in front of them. In this example we will create a simple structural directive *ngShow which will show/hide the embedded content based on a condition. Let us start by creating a new directive using the following ng command.

Custom Structural Directive

Structural directive in Angular alter the DOM by adding/removing elements to the DOM based on specific conditions.  Attribute directives on the other hand can be used to app specific properties / styles to the element which is using the directive. We saw the example of the highliter Attribute directive which added a background color for highlighting the element which uses the directive.

ngIf is a built-in structural directive, based on the condition/expression we pass to this directive we can show/hide a block of elements in the DOM. Structural directives are represented with a * symbol before the directing like *ngIf.

Monday, November 26, 2018

Passing values to Custom Attribute Directive

In the Highlighter directive custom attribute directive example we saw how to create a custom attribute directive and use it in a component. In the Highlighter directive example we just had to add the directive name in the HTML element and that’s it the directive used ElementRef to get a handle of the DOM element and set the background color of the element.

There are cases where we want to pass some values from the HTML element to the directive to perform more meaningful operations in the directive. To pass values to the Directive class we have to declare the parameters as @Input in the directive class as follows.

export class ExpValidatorDirective implements OnChanges  {
  @Input() expression: string
  ...
}

And when using the directive in the Component, we can pass values to the directive like properties as follows.

<span expValidator [expression]="value to be passed to the Directive"> </span>

In the following example we will create an Expression validator directive, this directive will take 2 parameters the first one is a regular expression and the second one is the value to evaluate. 

Sunday, November 25, 2018

Angular – ViewChild Decorator

The ViewChild decorator in Angular is used to query DOM elements in a Template or Directive or a Child component.

Accessing DOM elements can be done by adding a #reference to the element in the template and by using the ViewChild decorator in the component to get a handle to the element. The reference to the element will be available in the component only after the view initialization is completed, hence we can use this handle in the ngAfterViewInit lifecycle hook.

The following sample adds a reference #refInput to the template, and uses the reference to access the DOM element in the component.

Angular – ElementRef

Angular provides different ways to access the DOM elements directly in the component / directive instance. If you are familiar with react you can think of something similar to refs in react which provides direct access to DOM elements.

ElementRef is one of the options provided in Angular to access DOM elements. ElementRef is bound to a single element and allows us to reference that element in the component class and alter the element. Angular also provides reference options like TemplateRef, ViewRef, ComponentRef and ViewContainerRef to reference DOM elements.

ElementRef comes in handy when we create custom directives, using ElementRef we can get a handle to the DOM element which uses the directive. Using the handle we can get/set properties from the DOM element.

Using ElementRef to access a DOM element directly is not a recommended approach and should be avoided if possible. Within a single component using ElementRef can be replaced with using model binding etc.

Custom Attribute Directive example

Custom Attribute directives can be attached to HTML elements like input, span etc to provide more features / functionalities to the element. Custom directives can be created using the ng generate directive command. Similar to components which use the @Component decorator, a directive uses the @Directive decorator. The directive class can implement the life-cycle hooks and alter the bahaviour of the directives.

In the following example let us create a very simple Highlighter directive which can be used in a label/span tag and will highlight the label with a color. Let us begin by creating a new directive using the ng generate command as follows.

Wednesday, November 21, 2018

Angular Custom Directives

Directives in angular are special notations which allows us to extend the behavior of DOM elements in the view template. Like components directives also have a selector and used in the view template to extend the functionality of HTML tags. When the Angular compiler finds a directive in the view template it executes the class behind the directive and modifies the DOM accordingly.

Angular provides built-in directives like ngIf, ngFor etc, apart from these we can also define our own custom directives and use them in the view template.

Custom directives can be created using the ng generate directive command as follows.

Monday, November 19, 2018

Types of Angular Directives

Angular has 3 different types of directives
       1.       Component Directive 
       2.       Structural Directive &
       3.       Attribute Directive

What is an Angular Directive


Directives in angular are special notations which allows us to extend the behavior of DOM elements in the view template. For example the ngFor is a built-in Angular directives, the ngFor directive is used to repeat a set of HTML elements for a predefined number of times thereby creating a table/list structure in the view template.

Directives are not totally new to the Angular world, we had directives like ng-repeat in AngularJS which did the same thing as ngFor. Since Angular has evolved from AngularJS, the Directives structure and templates have also evolved with it since Angular 2+

Directives are classes declared using @Directive. Directives also have different life-cycle hooks which we can implement to alter the behavior of the Directives.

A new directive can be created using the following CLI command.

ng generate directive

Sunday, November 18, 2018

Angular Lifecycle Hooks

ngOnDestroy lifecycle hook


The ngOnDestroy lifecycle hook gets executed just before Angular destroys the directive/component. Use this event to unsubscribe Observables and detach event handlers to avoid memory leaks.  It is the perfect place to clean the component. Let us see on how to use this lifecycle hook with a simple example.

Similar to our ngOnOnit example, we have a service call using an observable to make a http ajax call to get data from a service, in this example we will use the ngOnDestroy hook to unsubscribe the observable and do a cleanup when the component in unloaded.

ngDoCheck lifecycle hook

The ngDoCheck lifecycle hook gets executed when Angular runs the change detection process. ngOnChanges also gets executed when changes are detected the difference is that ngOnChanges() detects changes for those properties which are passed by value. ngDoCheck() detects changes for those properties also which are passed by reference such as arrays. For performance reasons OnChanges does not fire when the input property is an array/object, in these cases we can use ngDoCheck to perform our own custom change detection.

Let us see how this works with a simple example. We will extend the example which we used for ngOnChanges, we will add one more @Input property to the child component, this time we will add an object instead of a string so that we can see that ngDoCheck gets triggered but not ngOnChanges when the object is changed.

ngOnInit lifecycle hook

The ngOnInt lifecycle hook is executed when the component is initialized, this event can be used to initialize data required by the component. The most common use of this event is to make ajax/api calls to fetch data required to be populated in the component. We can also use this event to initialize properties of the component. This hook gets executed after ngOnChanges() and before any child components are initialized.

Let us see how this works with a simple example. In this example we use the ngOnInit() event to call a service method which uses an Observable to get API data from a service. The response data is stored in a userList object, which can be rendered in the component UI.

ngOnChanges lifecycle hook

The ngOnChanges lifecycle hook is executed when any of the components data-bound input properties are changed. Let us see how this works with a simple example.

We have a parent component which has a nested child component. The parent component has a property “message”, the component also has a button on click of which we change the text of the message property in the button’s click handler. We embed a child component and pass the message as an @Input property to the child component. When we click the button in the parent component the message property changes and hence the value passed in the @Input property will also change, this should trigger the ngOnChanges lifecycle hook in the child component.

Saturday, November 17, 2018

Lifecycle hooks of an Angular Component


The following are the lifecycle hooks of an Angular component/directive. These life cycle hooks are executed in the order listed below.

What are Lifecycle Hooks?


An Angular component goes through different stages when it is initialized, changes and destroyed these stages are called lifecycle hooks. These lifecycle hooks helps us interact with the components and its properties through the various stages before it is rendered in the browser, we can make use of these lifecycle hooks to alter the behavior of the component. The constructor is the first method to be executed before any of the lifecycle hook is executed.

At a high level Angular application processing consists of the following 3 stages.

Tuesday, November 13, 2018

Angular Modules

Binding in Angular 6

Angular Basic Examples

Angular Overview

Preloading modules in Angular

We saw different ways of loading modules in an Angular Application
Eager loading
Laze Loading &
Pre Loading

Monday, November 12, 2018

Lazy Loading module example

Let us see how Lazy loading is implemented using a simple example. Let us start with creating a new Angular application using the ng new command as follows.

ng new LazyLoadApp -app --routing

Lazy loading modules in Angular


Lazy loading refers to loading modules with a delay, it is suitable for medium to larger applications where the number of dependent modules are more and loading all of them during the initial load is not feasible. In lazy loading each route is mapped to a module, but the module is not loaded till the route is invoked. Initial loading of the application will be quick since only the root module gets loaded when the application loads in the browser.

To implement Lazy Loading we need a root module and a one or more feature modules. In the routing configuration of the route module we map each route to one of the feature modules, when the route is invoked the corresponding feature module is loaded dynamically and rendered in the browser.

Sunday, November 11, 2018

What’s new in Angular 7

Angular 7 was released in October’ 2018.  Angular 7 provides new cli prompts which creating new angular objects like Components, Services etc.

For example when we use ng new command will prompt if the user wants to add routing, and provide options for different types of routing. The command ng add @angular/material will prompt the user if they want to include ng add @angular/material

Angular Universal

Angular Universal is a concept which enables server side rendering (SSR) of Angular applications. By default Angular applications are executed in the browser and rendered to the user. With server side rendering the Angular application is compiled into HTML in the server side and sent to the browser as HTML this enables quick rendering of the page in the browser.

Usually the server side rendering is used to render the first page of a website so that the user does not have to wait long once he hits the URL in the browser. Once the first page is rendered to the user, the Angular application gets downloaded to the browser and the subsequent requests will be server by processing the Angular application. Without server side rendering the user has to wait for the Application to be downloaded and processed in the client side before he sees the first page.

Friday, November 9, 2018

Observables in Angular

We saw that are a way of implementing asynchronous streaming operations, where an observable observables can emit multiple values to its subscribers. 

Angular used observables internally for various features like EventEmitters, Http service to implement Ajax calls, and in the routing module to handle route requests.

Angular provides an EventEmitter class that is used when publishing values from a component through the @Output() decorator. EventEmitter extends Observable, adding an emit() method so it can send arbitrary values.

Angular’s HttpClient returns observables from HTTP method calls. Previously we were using promises to implement ajax calls, Angular uses Observables by default.

Router.events provides events as observables. You can use the filter() operator from RxJS to look for events of interest, and subscribe to them in order to make decisions based on the sequence of events in the navigation process.

Below is a sample code implementation of using observables in Angular services to make Ajax calls, and the component code to subscribe and use the data from the observable.

RxJS Observables

RxJS stands for Reactive Extension for JavaScript. As the name implied RxJS is used to implement reactive programming in JavaScript. Reactive programming deals with implementing asynchronous streams. RxJS provides an implementation of Observable type which is used in Angular to implement a producer – subscriber pattern.

An observable is a function that produces a stream of values and emits it to its subscribers over time
. When you subscribe to an observable, you are an observer. Observer receive the emitted values.

Observables can emit 3 types of notifications

next – To emit the next value in the list
complete – When the observable is done with emitting all the values
error – When an error occurred in the observable.

We can understand how the observables and observer work with a simple example as follows.

Thursday, November 8, 2018

What are Observables

Observables provide a new way of passing data asynchronously between a publisher and a subscriber. Observables can be used to pass multiple values from a publisher to its subscribers over time.

A publisher creates an instance of Observable and defines a subscribe() function. When a subscriber subscribes to the publisher this function will get executed. The function will not get executed till a subscriber subscribers.

Observables are like an array of items which are delivered to the subscribers over a period of time. Angular uses observables internally in its event system and in the Http service. Observables are not built into Angular, instead Angular uses a library RxJs to implement observables.

Promises can also be used to make asynchronous Http calls. The advantage of observables over promises is that promise can deliver only one value, while observables can deliver a list of values over time. Also promises cannot be cancelled once initiated, while observables can be cancelled at any time.

Sunday, November 4, 2018

Angular Routing

Routing in Angular is used to load different components based on the route selected by the user. Routing is essential for medium to larger size applications since we cannot load all the components in a single view.

If you have worked on MVC applications you know that there is a route handler which parses the request route and redirect to the corresponding view. Angular Routing is similar the Routing module handles the request route and loads the corresponding component.

The routing services in Angular are present in the package @angular/router
, we need to import RouterModule, Routes from this package to implement routing in Angular.

Friday, November 2, 2018

JIT vs AOT compiler in Angular

Angular applications consists of components and service classes written in TypeScript and HTML templates. Browsers cannot understand TypeScript hence they need to be compiled into JavaScript.

Angular provides 2 types of compilers for this compiling process.


1. Just-In-Time (JIT) compiler.
2. Ahead-of-Time (AOT) compiler

Angular AOT Compiler

AOT stands for Ahead of Time. AOT compiler helps pre-compile Angular applications so that they can be rendered faster in the browser.

We know that Angular applications consists of components and service classes written in TypeScript and HTML templates. Browsers cannot understand TypeScript hence they need to be compiled into JavaScript.

Angular provides 2 types of compilers for this compiling process.


Thursday, November 1, 2018

Eager loading Module example in Angular 6

Eager loading is the default type of module loading in Angular, this approach is suitable for smaller applications where all the dependent modules are loaded initially when the application is loaded in the browser.

In eager loading we import all the dependent components into the main module and map the components to different routes in the module routing. When a specific route is invoked the corresponding component is loaded in the root component.

This example is similar to the one which we saw in the Routing example. We import 2 components About & Contact in the application module and map them in the modules routing configuration.