Tuesday, July 26, 2016

Angular2: Barrel

Angular2 Barrel is a way to encapsulate multiple module export into single unit. It helps to reduce multiple import statements in module.  It’s index.ts or index.d.ts file where modules are exported. Now to import modules we don’t need to import them separately. This barrel is gateways where we can import all the modules are re-exported.

According to angular.io documentation “A barrel is a way to rollup exports from several modules into a single convenience module. The barrel itself is a module file that re-exports selected exports of other modules.

Let’s say we have three modules dashboard.component.ts, dashboard.routes.ts, dashboard.service.ts. also we have index.ts(Barrel).

now in index.ts(Barrel) we have the code as 

export * from './dashboard.component';
export * from './dashboard.routes';
export * from './dashboard.service';

import { Component} from '@angular/core';
export class DashboardComponent {  constructor() {}}

import { RouterConfig } from '@angular/router';
export const DashboardRoutes: RouterConfig = [  ……];

import { Injectable } from '@angular/core';
export class DashboardService {  constructor() {}} 

Now I have to use above module in app component.  So I will be importing without barrel into app.component
import { DashboardComponent } from ' dashboard.component’;
import { DashboardRoutes } from ' dashboard. routes’;
import { DashboardService } from ' dashboard. service’;
As we can see we need to write three line of code. assume if we have 10-20 modules exported from same same place. Now with barrel we can write the same import statement as 
 import { DashboardComponent, DashboardRoutes,  DashboardService } from ' dashboard;
import * as dash from ' dashboard; 
Again "import * as dash from ' dashboard;" is not suggested as while compiling it will import all the modules present with barrel even if that is not required. its better to import specific modules.

Friday, July 15, 2016

Angular2: A learning approach.

We all know JavaScript development practice is moving to ES6 & typescript. Most of the Interactive developers are updating their skillset to ES6 & Typescript. Being Angular based Interactive developer we too have a change coming i.e. Angular2. Here we have three choices to go with AngularJS.
  1. Angular2 for JavaScript.
  2. Angular2 for Typescript.
  3. Angular2 for Dart.

Typescript is a typed super set of JavaScript which has been built and maintained by Microsoft and chosen by the AngularJS team for development. The presence of types makes the code written in Typescript less prone to run-time errors. Typescript may help us to write angular hooks easily at a later point of time. So Angular2 for Typescript is the better option.


I started looking for Angular2 tutorial. I found it’s completely changed from Angular1.  In Angular1 I was having bower and npm for package manager. When started with Angular2 first wander was bower package manager. Angular2 was not available in Bower (Dev version is there). Quora (https://www.quora.com/Why-is-Angular-2-not-available-in-Bower) gave me answer saying typescript compilation from ES6 to ES5 require node. It cannot be import to HTML directly without compiling. So bower is of no use here. I am not exploring much on bower side for now. I guess it needs some workaround to know its possibility and I am expecting it to be possible.

Angular Template:

There are multiple templates available forAngular2. But from the time google started Angular-CLI, it has become the best template. So I started my learning with angular-cli from https://cli.angular.io/ .


To start with AngularCLI we need latest node to be installed on our system as the basic requirement. Having lower version may not support Angular-CLI. Get the latest version of node from https://nodejs.org/en/ .  here we may have to install typings with command (npm install -g typings). Next we have to install angular-cli from command prompt or terminal. Let’s execute

npm install –g angular-cli

Now our Platform is ready to start with angular-cli.  So create a new project with

ng new <project_name>

it will create an angular-cli project. Just navigate to project directory & start the server as:

cd <project_name>
ng serve.

Open Browser & navigate to http://localhost:4200/ . It will say application works.
More details can be found at https://github.com/angular/angular-cli.
Here everything looks so easy.  Just follow the steps, execute ng serve & application is running.

Bootstrap CSS

To add bootstrap styling just add CDN resource or bootstrap.css file to the src directory and link it in index.html file. Better to go with CDN resource.

SASS Support:

To enable sass install node-sass as

npm install node-sass

and rename .css files to .scss. in /dist  folder it will create compiled respective .css files.


Now the question came where will I create my page layout?
For page layout the perfect place is app.component.html. Here we can draw the layout we want for our page. & with the help of component selector we can decorate our page. Let’s create a component with name “top-navigation” as

ng g component top-navigation

it will create 4 files .html, .ts, .css, .spec.ts inside top-navigation folder. Now go to app.cmponent.ts update the file with

import { TopNavigationComponent } from './top-navigation/top-navigation.component'; in import section. Remember TopNavigationComponent is component name and inside from we need to provide the respective path.

and directives: [TopNavigationComponent] inside @Component.

and <app-top-navigation></app-top-navigation> inside app.component.html.

If any respective css is required for top-navigation component, update top-navigation.component.css.
Note: Here I am integrating top-navigation template inside app.component.html.  so importing top-navigation component inside app.component.


When considering page navigation we are supposed to use route.  Let’s add a router to application by executing ng generate route login

Oops it failed to create route files saying.

“(node:12032) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
Due to changes in the router, route generation has been temporarily disabled. You can find more information about the new router here: http://victorsavkin.com/post/145672529346/angular-router

They have mentioned “The Component Router is in beta release. This is the recommended Angular 2 router and supersedes the earlier deprecated beta and v2 routers.”

Just Check package.json, what dependency is mentioned with rc.3?

Update them as rc.4 so it will look like
    "@angular/common": "2.0.0-rc.4",
    "@angular/compiler": "2.0.0-rc.4",
    "@angular/core": "2.0.0-rc.4",
    "@angular/forms": "0.2.0",
    "@angular/http": "2.0.0-rc.4",
    "@angular/platform-browser": "2.0.0-rc.4",
    "@angular/platform-browser-dynamic": "2.0.0-rc.4",
    "@angular/router": "3.0.0-beta.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.4",

Update these packages with npm install.

I am considering we already have created ‘login’ & ‘dashboard’ component. So let’s tell our application that I am going to add router to application by updating main.ts with

import { appRouterProviders } from './app/app.routes';

and update the bootstrap as

bootstrap(AppComponent, [appRouterProviders]);

Now create a route file manually say ‘app.routes.ts’.

import { provideRouter, RouterConfig } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.Component'
import { LoginComponent } from './login/login.component'

const routes: RouterConfig = [
  { path: 'dashboard', component: DashboardComponent },
  { path: 'login', component: LoginComponent },
  { path: '', component: LoginComponent}

export const appRouterProviders = [

Here to route we have configured our RouterConfig with path & component. Since to navigate we need a component, so respective component import is required.  “path: ''” is for creating a default route.

Now update app.component.ts with import.

import { ROUTER_DIRECTIVES } from '@angular/router';

next directives: [ROUTER_DIRECTIVES] inside @Component.

next <router-outlet></router-outlet> inside app.component.html, it tells the layout that routed 
component content will come inside.

Now hit the URL with login & dashboard, It will navigate to respective component.

Navigation from DOM:

Now update top-navigation.component.ts with import.
import { ROUTER_DIRECTIVES } from '@angular/router';

next directives: [ROUTER_DIRECTIVES] inside @Component.
and <a [routerLink]="['/dashboard']" >Dashboard</a> inside app.component.html . wherever navigation link is required.

If navigation has to appear on button click then html content will be like
<button type="button" (click)="dashboardNav();"> dashboard </button>

For this we need a method in respective component.ts as below

  dashboardNav (){

And here constructor will be like

constructor(private router: Router) {}

Yep Ready to go. Just execute ng serve & enjoy.
I guess it may help. :)

Thursday, March 12, 2015

Create 3D graphics using three.js.

Being a JavaScript developer if we want to create 3D visualization, we have a great native support from webgl (Web Graphics Library). But Again If we are going to draw a Cube using webgl it needs more that 500 Lines of code. But on the same time we have some 3D library, which are Like a Wrapper on webgl & using them we can draw the same cube in Less than 50 Lines. Now I don't need to write 500 lines of code. But i can get all the features of webgl with these wrappers as well. Let’s have a look on webgl features.

  1. It's a JavaScript API for rendering interactive 3D graphics and 2D graphics within any compatible web browser without the use of plug-ins.
  2. It brings 3D graphics to the Web by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 <canvas> elements.
  3. Complicated in comparison to other web technologies because it's designed to work directly with graphics card.
  4. Drastically decrease the amount of code we need to write. While a simple cube in raw webgl turns out hundreds of lines of shader and JavaScript code, a Three.js equivalent is only a part of that.
  5. Most of them build on top of webgl to create elements intuitive to a 3D environment like a scene, a camera, a light source, ambient light, ready-made shapes, materials, textures, and effects such as fog, and floating particles.
  6. Most libraries provide easy ways to handle events and vertex and fragment shaders, small programs that run on GPU

This is all about webgl features. Now have a look on some notable Library based on webgl

  1. Three.js (Three GitHub repo) - Three.js is a lightweight 3D engine with a very low level of complexity. The engine can render using <canvas>, <svg> and webgl.
  2. PhiloGL (PhiloGL GitHub repo) - PhiloGL is built with a focus on JavaScript good practices and idioms. Its modules cover a number of categories from program and shader management to XHR, JSONP, effects, web workers and much more.
  3. GLGE (GLGE GitHub repo) - GLGE has some more complex features, like skeletal animation and animated materials.
  4. J3D (J3D GitHub repo) - J3D allows you not only to create your own scenes but also to export scenes from Unity to webgl.
  5. SceneJS (Scene GitHub repo) - SceneJS is an extensible webgl-based engine for high-detail 3D visualization using JavaScript. Specialized towards fast rendering of large numbers of individually articulated objects, like in CAD, without game engine effects like shadows, reflections etc. Less flexibility than three.js, GLGE and PhiloGL.
  6. Babylon.js(Babylon GitHub Repo) – Suitable for Game Creation due to features such as collision detection

Amongst All mention above we have very good popularity (18000+) & Support from Stack-overflow as well as good number of contributors (443+) with Three.JS. With Other Library all these figures are very less.

About ThreeJs:
  • A lightweight cross-browser JavaScript library/API.
  • Can be used in conjunction with the HTML5 canvas element, SVG or webgl.
  • Has a great fall-back feature. ThreeJs can fall-back to use canvas for rendering if webgl is not available.
  • A fraction of webgl code.
  • Just need to understand the webgl concepts, does an excellent job of abstracting away many of the details of webgl.
  • Allows the creation of GPU-accelerated 3D animations using the JavaScript language as part of a website without relying on proprietary browser plugins.
  • ThreeJs come with exporters that will take 3DS and FBX and translate these into JSON files readable by ThreeJs. It also comes with Blender export and import JSON files.

To start with ThreeJs rendering we need to know what are the features ThreeJs have. Like Any movie shooting I would like to say "Lights-camera-Action". On Action our Object has to be in Scene. Let’s us have an idea what is Lights Camera & Action.SceneThreeJs uses the concept of a display list. This means that all objects are stored in the list and then drawn to the screen. Here, it's a THREE.Scene object. To draw an object on the screen add the Object to scene.RendererThe renderer simply draws everything from the scene to the webgl canvas.
  • Canvas Renderer
The Canvas renderer displays scenes using the Canvas 2D Context API.renderer = new THREE.CanvasRenderer();
  • WebGL Renderer
The webgl renderer displays scenes using webgl, if your device supports it. This renderer has way better performance than CanvasRenderer.renderer = new THREE.WebGLRenderer();Both WebGLRenderer and CanvasRenderer are embedded in the web page using an HTML5 <canvas> tag. The "Canvas" in CanvasRenderer means it uses Canvas 2D instead of webglCameraCamera tells the renderer to from which point of view it should be render. Camera is of two types
Orthographic                                  Perspective
    • PerspectiveCamera

    camera = new THREE.PerspectiveCamera( fov, aspect, near, far )
    fov — Camera frustum vertical field of view.
    aspect — Camera frustum aspect ratio.
    near — Camera frustum near plane.
    far — Camera frustum far plane.

  • OrthographicCamera

  • camera=new THREE.OrthographicCamera (left,right,top,bottom,near, far)
    left — Camera frustum left plane.
    right — Camera frustum right plane.
    top — Camera frustum top plane.
    bottom — Camera frustum bottom plane.
    near — Camera frustum near plane.
    far — Camera frustum far plane.

Geometry is a set of points that need to be connected in order to create the object.
var geometry = new THREE.CubeGeometry(200, 1, 200);

Material is simply the paint that will cover the object.
var material = new THREE.MeshBasicMaterial({color:0XFFAA00, overdraw: true });

A mesh is an object that takes geometry, and applies a material to it, which we then can insert to the scene, and move freely around.
var cube = new THREE.Mesh(geometry, material);

Time for Action:

Let’s us have a module to render a cube as shown in below picture.
For that let's have a start with our HTML page.

<title>My first Three.js app</title>
canvas { width: 100%; height: 100% }
<script  src="three.js"></script>
<script src="custom.js"></script>

Here three.js is our library, & custom.js is our JavaScript code which will render 3D cube shown above.

Adding Scene Camera & rendere to initilize the App.
There are a multiple types of cameras in ThreeJs. For now, let's use a PerspectiveCamera.
var scene, camera, renderer;
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.x = 50;
    camera.position.y = 100;
    camera.position.z = 200;
    renderer = new THREE.WebGLRenderer();
     renderer.setSize(window.innerWidth, window.innerHeight);

Now Adding scene & camera to renderer
var render = function() {
    renderer.render(scene, camera);

Add Some Animation
Animating frames with render loop
var animate = function() {

Adding an Object to Scene
Now everything is ready, But nothing is getting Displayed guess why?  So let’s add an Object to display a mesh.

var getMesh=function(){
     var geometry = new THREE.CubeGeometry(10, 10, 10);
     var material = new THREE.MeshBasicMaterial({vertexColors: THREE.FaceColors, color:"red", overdraw: 0.5, opacity: 0.9});
     var cube = new THREE.Mesh(geometry, material);
     cube.position.x = 100;
     cube.position.y = 100;
     cube.position.z = 100;

Now just call the above function as.

getMesh(); // to render our cube into scene

Want some Extra Animation?? Let’s Update our Animation as

var animate = function() {
  1. cube.rotation.x += 0.1;
  2. cube.rotation.y += 0.1;

finally our code will look like

(function () {
    'use strict';
    var scene, camera, renderer, cube;
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.x = 50;
    camera.position.y = 100;
    camera.position.z = 200;
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    function animate() {
        cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;
    function getMesh(){
        var geometry = new THREE.CubeGeometry(50, 50, 50);
        var material = new THREE.MeshNormalMaterial({vertexColors: THREE.FaceColors, color:'red', overdraw: 0.5, opacity: 0.9});
        cube = new THREE.Mesh(geometry, material);
        cube.position.x = 50;
        cube.position.y = 100;
        cube.position.z = 100;
    function render() {
        renderer.render(scene, camera);

We Are Done. Our Cube is Displayed & rotating in the 3D plane. For Demo visit this link

Now We Saw that Creating a cube with ThreeJs is really handy & easier. It can be used for 3D charts & visualizations. Though ThreeJs supports blender exported data for 3D animation. If you are good with Blender, we can go with Animation's or interactive 3D computer graphics.