Electron with Angular 2 and Angular 2 CLI

In this tutorial ,we are going to build a starter project which shows you how you can use Electron with Angular 2 to build Desktop applications .The final project starter will be available from GitHub so feel free to clone it and start using it to build your Electron app with Angular 2 without reinventing the wheel .

But if you want to go through the process step by step ,lets get started .

The first thing you need to do is installing the Angular 2 CLI which is a nice tool inspired from ember-cli that allows you to quickly scaffold a new Angular 2 based project and also assists you during the development of your project by providing commands to scaffold different Angular 2 artifacts such as components ,routes etc .and provides you with a development server .So oepn up your terminal/command prompt and enter the following

npm install -g angular-cli

Make sure you have Node.js and NPM installed on your system but since your are working with Electron then you’ll definitely have them already installed .

Next we need to scaffold a new Angular 2 project

ng new electron-angular2-starter

cd electron-angular2-starter

ng serve

If you have no problem you should be able to visit your app from your browser by going to http://localhost:4200 .

You’ll have a nice “app works!” message displayed .

Now just go back to your terminal and enter CTRL+C to terminate the development server and then start integrating our Angular 2 project with Electron .

But before we continue you need to have Electron installed

npm install -g electron

Inside electron-angular2-starter create a folder with name ‘electron’

mkdir electron
touch main.js package.json

open up package.json and copy the following

  "name": "electron-angular2-starter",
  "version": "0.1",
  "main": "main.js"

Next open up main.js and copy the following code

const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
let mainWindow

function createWindow () {

  mainWindow = new BrowserWindow({width: 800, height: 600})



  mainWindow.on('closed', function () {
    mainWindow = null
app.on('ready', createWindow)

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {

app.on('activate', function () {
  if (mainWindow === null) {

Next go to your app src/index.html file and modify this line

<base href="/">


<base href="./">			  

Next we need to create some npm scripts which will make the process easy for us .

So open up your Angular 2 project package.json (exists on the root of your project folder )

Under scripts add these 3 scripts

"build": "ng build && cp -R src/public dist/public",
"postbuild": "cp -a electron/. dist",
"electron": "npm run postbuild && electron dist" 

For windows –


“build-electron”: “ng build –base-href . && copy src\\electron\\* dist”,
“electron”: “npm run build-electron && electron dist”


Now, let’s create “Package.json” for electron app


srs/electron –> package.json


  “name”: “angular2-electron-cli”,
  “version”: “0.1.0”,
  “main”: “main.js”


That’s it you can now build and run your project with

npm run build 
npm run electron

You should have your Electron app started with the “app works!” message just like in the browser .

Electron with Angular 2 and Angular 2 CLI


This tutorial comes to end .You can also find the complete project on GitHub .I hope this post was helpful for you and see you in next tutorials .

Angular 2 Errors

If you’ve begun to try out Angular 2, you might have encountered some pretty baffling errors. I know I sure did…

It always feels a bit frustrating to start fresh in a new library or language (or both, in this case) – all your previous experience goes out the window, and you’re back to making beginner mistakes and hitting confusing errors.

Here’s a list of some errors I ran into, my best guesses as to what caused them, and how I fixed them.

The relevance of these errors may (hopefully) decay over time – these ones were encountered in Angular 2 Beta 0 or a late Alpha version.

General Advice
  • If you get an error in the console, scroll to the top! The later errors are not very helpful. Look at the first one.

  • Some of these can be really tricky to track down. As a general strategy, make small changes and test as you go. At least that way it’ll be easier to figure out which bit of code broke (like when the stack traces are not so helpful).

  • Styles don’t seem to cascade to subcomponents by default… (this can be controlled by the encapsulation property of the @Component decorator. See the docs for more info.)

Errors, Errors, Everywhere…
EXCEPTION: TypeError: allStyles.map is not a function

‘styles’ needs to be an array of strings, not a single string.

EXCEPTION: Component ‘Something’ cannot have both ‘styles’ and ‘@View’ set at the same time”

I provided a @View decorator, and also put a ‘styles’ key in the @Component – this doesn’t work. Put ‘styles’ in the object passed to @View.

From Igor: Put everything in @Component and don’t use @View – it might be used in the future but it’s not needed right now.

EXCEPTION: Unexpected directive value ‘undefined’ on the View of component ‘AppComponent’

I defined a component as class Something when it should’ve beenexport class Something – forgot to export it from the file it was defined in. The importdidn’t fail, but the directives: [Something] did…

From Igor: This is a problem with polyfilling ES Modules. Something outside of Angular, and in fact a well known issue with all ES module polyfills. Once we have a native implementation you will get an error, but in the meantime if you use the TypeScript compiler you’ll get a compile time error.

EXCEPTION: No provider for UserList! (UserCmp -> UserList)

I forgot to add UserList to the viewProviders array in the parent view. The fix was@Component({viewProviders: [UserList]})

EXCEPTION: Cannot resolve all parameters for UserList(?). Make sure they all have valid type or annotations.

I got this when I was trying to inject the Http service.

For WHY this happens, see Injecting services in services in Angular 2.

There are 2 different ways to fix this:

Way #1 (preferred): Put @Injectable() above the class (don’t forget the parens!)

This is the way to go if you’re using TypeScript.

constructor(public http: Http)

Way #2: Put @Inject(Http) before the param that should be injected with Http:

From Igor: If using TypeScript you should almost never use @Inject because@Injectable is less verbose and easier to understand. @Inject should primarily used by ES6 users that don’t use TypeScript.

// This doesn't work :(
constructor(public http: Http)

// This works :)
constructor(@Inject(Http) public http: Http)

EXCEPTION: Error during instantiation of UsersCmp

TypeError: this.http.get(…).map is not a function

I thought TypeScript was supposed to save us from TypeErrors!

Removing .map fixed the error… but it seems like it should work. I don’t know too much about this new Http service so, maybe the request failed?

Nope: You have to explicitly include the map operator from RxJS. Awesome. Add this line to app.ts (or whatever your main file is):

import 'rxjs/add/operator/map';

From Igor: This is an intentional trade off we made as a part of larger effort to curb the uncontrolled increase in payload size. The current behavior sucks. The right fix is to get the pipe operator through TC39 and have it implemented in TypeScript and Babel.

EXCEPTION: Cannot find a differ supporting object ‘[object Object]’ in [users in UsersCmp@2:14]

I’m pretty sure this means that a non-array was passed to ngFor. Make sure the thing you pass is an array.

Compile error: “Type ‘Observable’ is not assignable to type ‘any[]’.”

Got this when I was trying to return this.http.get() as any[] – it’s not an array, so that doesn’t work. Changing to any works better (or the actual type, for that matter).

and my personal favorite:

EXCEPTION: [object Object]

WTF? Caused by:

return this.http.get('/users/list')
    .map(res => res.json())
    .subscribe(users => this.users = users); // this line. Why?

Without an error handler, a 404 response causes an exception.

Call subscribe this way instead:

	res => res.text(), 						// success
	err => handleErr(err),				// error
	() => console.log('done'));		// done

Angular 2.0 – Style Guide / Architecture

Community-driven set of best practices and style guidelines for Angular 2 application development



logo Angular 2 Style Guide

The purpose of the following style guide is to present a set of best practices and style guidelines for the development of Angular 2 applications. If you are looking for an opinionated style guide for syntax, conventions, and structuring Angular 2 applications, then you can step in!

Good compilation of all resources from https://mgechev.github.io/angular2-style-guide/

Happy Coding

Angular 2.0 Architechture

Starting new series – Learning Angular 2.0 on My Github –


##### angular 2.0 building blocks
– Module
– Component
– Template
– Metadata
– Data Binding
– Service
– Directive
– Dependency Injection

##### 1. Module
– Angular apps are modular and so in general we assemble our application from many modules. A typical module is a cohesive block of code dedicated to a single purpose.
– A module exports something of value in that code, typically one thing such as a class.
– Some modules are libraries of other modules.
– Angular itself ships as a collection of library modules called “barrels”. Each Angular library is actually a public facade over several logically related private modules.
– The angular2/core library is the primary Angular library module from which we get most of what we need.
– There are other important Angular library modules too such as angular2/common, angular2/router, and angular2/http.
– e.g import {Component} from ‘angular2/core’;
– The key take aways are:
    – Angular apps are composed of modules.
    – Modules export things — classes, function, values — that other modules import.
    – We prefer to write our application as a collection of modules, each module exporting one thing.
    – The first module we write will most likely export a component.

##### 2. Component
– Perhaps the first module we meet is a module that exports a component class. The component is one of the basic Angular blocks, we write a lot of them
– Most applications have an AppComponent. By convention, we’ll find it in a file named app.component.ts
– Components are the collection of templates, styles, selector configurations etc.
– Angular creates, updates, and destroys components as the user moves through the application.
– Each components is a typescript class which again includes variable, functions, prop declaration etc.

##### 3. Template
– We define a Component’s view with its companion template. A template is a form of HTML that tells Angular how to render the Component.
– A template looks like regular HTML much of the time … and then it gets a bit strange.
– Template will have all diff type databinding and html DOM information.

##### 4. Metadata
– Metadata tells Angular how to process a class.
– e.g
  selector:    ‘hero-list’,
  templateUrl: ‘app/hero-list.component.html’,
  directives:  [HeroDetailComponent],
  providers:   [HeroService]
Here we see the @Component decorator which (no surprise) identifies the class immediately below it as a Component class.

selector – a css selector that tells Angular to create and insert an instance of this component where it finds a <hero-list> tag in parent HTML. If the template of the application shell (a Component) contained

templateUrl – the address of this component’s template

directives – an array of the Components or Directives that this template requires.

providers – an array of dependency injection providers for services that the component requires. This is one way to tell Angular that our component’s constructor requires a HeroService so it can get the list of heroes to display.

##### 5. Data Binding
– There are four forms of data binding syntax.
– Each form has a direction – to the DOM, from the DOM, or in both directions.
– We can group all bindings into three categories by the direction in which data flows. Each category has its distinctive syntax:
    – One Way (from component -> View)   – Binds Property, Attributes, Class, Style.
    [target] = “expression”
    bind-target = “expression”
    – One Way (from View -> Component) – Binds Events
    (target) = “Statement”
    – Two way binding
    [(target)] = “expression”
    bindon-target =”expression”
For More Details – https://angular.io/docs/ts/latest/guide/template-syntax.html

##### 6. Directive
– Our Angular templates are dynamic. When Angular renders them, it transforms the DOM according to the instructions given by a directive.
– A directive is a class with directive metadata. In TypeScript we’d apply the @Directive decorator to attach metadata to the class.
– While the component is technically a directive, it is so distinctive and central to Angular applications that we chose to separate the component from the directive in our architectural overview.
– There are two other kinds of directives as well that we call “structural” and “attribute” directives.
– Structural directives alter layout by adding, removing, and replacing elements in DOM.
    – e.g *ngFor , *ngIf etc.
– Attribute directives alter the appearance or behavior of an existing element. In templates they look like regular HTML attributes, hence the name.
    – e.g. [(ngModel)]

##### 7. Service
– “Service” is a broad category encompassing any value, function or feature that our application needs.
– Almost anything can be a service. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.
    – Examples include:
        – logging service
        – data service
        – message bus
        – tax calculator
        – application configuration
– Most common usage of services are to bind components with Databases or any similar part which delivers data to components and that way, components will be independent from Data Layer.

##### 8. DI (Dependency Injection)
– “Dependency Injection” is a way to supply a new instance of a class with the fully-formed dependencies it requires. Most dependencies are services. Angular uses dependency injection to provide new components with the services they need.
– dependency injection is wired into the framework and used everywhere.
– the Injector is the main mechanism.
    – an injector maintains a container of service instances that it created.
    – an injector can create a new service instance using a provider.
– a provider is a recipe for creating a service.
– we register providers with injectors.

##### 9. Other Stuff
– Animation: A forthcoming animation library makes it easy for developers to animate component behavior without deep knowledge of animation techniques or css.
– Bootstrapping: A method to configure and launch the root application component.
– Change Detection: Learn how Angular decides that a component property value has changed and when to update the screen
– Zones: Change Detection uses zones to intercept asynchronous activity and run its change detection strategies.
– Events: The DOM raises events. So can components and services.
– Router: With the Component Router service, users can navigate a multi-screen application in a familiar web browsing style using URLs.
– Forms: Support complex data entry scenarios with HTML-based validation and dirty checking.
– Http: Communicate with a server to get data, save data, and invoke server-side actions with this Angular HTTP client.
– Lifecycle Hooks: We can tap into key moments in the lifetime of a component, from its creation to its destruction, by implementing the “Lifecycle Hook” interfaces.
– Pipes: Services that transform values for display. We can put pipes in our templates to improve the user experience.
    price | currency:’USD’:true
– Testing: Angular provides a testing library for “unit testing” our application parts as they interact with the Angular framework.

### Author
Bhavin Patel

Happy Coding Smile

Angular 2.0–Beginners Guide


A curated list of helpful material to start learning Angular 2

Basic Introduction Video Series by Mindspace and Code Samples by me (Bhavin Patel)
(Video Series link is in my github)



Angular 2 Explained

Angular 2 Forms

Angular 2 Docs

Angular 2 Integrations




Example Apps

Live Code Experiments

Angular 2 Material

Stack Overflow Questions





Social Media

Angular 2 Dart

TypeScript Definitions

Thanks to  timjacobi/angular2-education for this great compilation.

Happy Coding Smile

angular- Dynamic window height with ng-style

Recently, I was working on one nw.js (Node-webkit) related project for creating windows / desktop application using node/nw.js. I had to write window resize event and based on that I needed to show vertical scrollbar.

in short something like – where height and scrollbar will adapt window resize automatically upon resize.


angular code

app.directive(‘winResize’, function ($window) {
    return function (scope, element, attr) {

        var w = angular.element($window);
        scope.$watch(function () {
            return {
                ‘h’: window.innerHeight,
                ‘w’: window.innerWidth
        }, function (newValue, oldValue) {
            console.log(newValue, oldValue);
            scope.windowHeight = newValue.h;
            scope.windowWidth = newValue.w;

            scope.resizeWithOffset = function (offsetH) {
                return {
                    ‘height’: (newValue.h – offsetH) + ‘px’                   

        }, true);

        w.bind(‘resize’, function () {

HTML code


window.height: {{windowHeight}}

window.width: {{windowWidth}}

Hope this helps someone in need…!! Happy Coding Smile

How-to: node.js Logger–winston setup / configuration

I am working on node.js based REST API development and I am using this very popular npm middleware called “Winston” for logging errors, exceptions and even info & debug log too.

Why we need it?

Now you must be wondering why we need it since we already have console.log to check logs while development, BUT what happens when we decide to go live? How to access the logs? How to create different log levels?

Well, WINSTON is your answer… following is the setup and configuration.

Manual Logging

If you want to log only specific things that you want to track, there are easy libraries that let you do so. Winston is a very popular one. You can log your output to multiple transports at the same time (e.g: file, console…). It’s also supported by 3rd parties cloud services that will be happy to host those outputs for you (more about that next). 

Here is a simple snippet of how to configure winston and log it to both your console and a file: 


var winston = require('winston');

//log your output to a file also

winston.add(winston.transports.File, { filename: 'somefile.log' });

//log some outputs

winston.log('info', 'Hello distributed log files!');

winston.error('Who let the dogs out?!');

How if you want dedicated log files to have all log written to it? which is idle for production anyways –  Here is my setup

– Create folder “helpers” in your project & create “logger.js” in that folder.

– logger.js code


– Now in your server.js or app.js (your main node startup file) add this middleware declaration

var logger = require(‘./helpers/logger.js’);

– That’s it…. You are all set…verify by logging any simple information like –

logger.info(‘this is information’);

logger.debug(‘this is debug’);

logger.warn(‘this is warning’);

logger.error(‘this is error’);

Thanks to Winston development team & of course sweet node.js…

Happy Coding Smile

How-to with Node.jS & file system

1. Reading from a file

You want to read a file from the file system and display its contents on the terminal screen.

var fs = require('fs');
fs.readFile('data.txt', function (err, data) {  if (err)    throw err;  if (data)    console.log(data.toString('utf8'));

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs. The next line states our input file ‘data.txt’. The next part of this line will attach our anonymous callback function function (err, data) to the actual file read operation readFile.

Our anonymous callback function accepts any errors which occur as  err, and the resulting file data as a binary buffer array  data. Within the anonymous function, we first check for any potential errors and throw the error as an exception to be left to be caught by the calling process as if (err)  throw err; . The subsequent lines check to see if the data is not null, and then converts the data to a UTF-8 encoded string to be written to the console screen if (data) console.log(data.toString(‘utf8′));

It is important to note that this solution uses the asynchronous file read operation to prevent blocking. For a synchronous, or blocking file read operation, reference the Node.js documentation for readFileSync()

var fs = require('fs');
fs.writeFile('data2.txt', 'Hello, World!', function (err) {
     if (err)
       throw err;

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs.  The next line states our input file ‘data2.txt’ along with a string of the text we want to write to the file ‘Hello, World!’. The next part of this line will attach our anonymous callback function function (err) to the actual file write operation writeFile(). Our anonymous callback function accepts any errors which occur as  err. Within the anonymous function, we also check for any potential errors and throw the error as an exception to be left to be caught by the calling process as if (err)  throw err; .
It is important to note that this solution uses the asynchronous file write operation to prevent blocking. For a synchronous, or blocking file write operation, reference the Node.js documentation for writeFileSync()

3. Working with directories

You want to read through a list of all of the files in a given directory location and display each file’s name.

var fs = require('fs');
fs.readdir('.', function (err, files) {
 if (err)
    throw err;
 for (var index in files) {

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs.  The next line states our input directory ‘.’ (the current working directory). The next part of this line will attach our anonymous callback function function (err, files) to the actual directory read operation readdir(). Our anonymous callback function accepts any errors which occur as  err and an array of filenames stored in files.

Within the anonymous function, we first check for any potential errors and throw the error as an exception to be left to be caught by the calling process as if (err)  throw err;. Next we iterate over each item in the filename array and display each filename on the console screen.

It is important to note that this solution uses the asynchronous directory read operation to prevent blocking. For a synchronous, or blocking directory reading operation, reference the Node.js documentation for readdirSync()

4. Traversing the file system

You want to recursively read through a list of all of the files in a given directory location and display each file’s name or recursively traverse the file if it is a directory.

 var fs = require('fs');
 var traverseFileSystem = function (currentPath) {
    var files = fs.readdirSync(currentPath);
    for (var i in files) {
       var currentFile = currentPath + '/' + files[i];
       var stats = fs.statSync(currentFile);
       if (stats.isFile()) {
      else if (stats.isDirectory()) {

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs.  The next line defines our custom function traverseFileSystem which accepts one parameter currentPath which contains the current directory path the function is traversing.

The first line of this function simply displays the current directory’s name. Next we synchronously return a list of files contained in the current directory (this is done synchronously to guarantee we have a list of files before we try to traverse them). Next we iterate over each item in the filename array. From here we create a variable to store our fully-qualified file path and obtain information about that file using a synchronous file stats call  statSync() (this function is described in more depth in the next example).

The function then checks if the current file is a file or a directory, and either displays the file’s name if it is a file or recurses by re-invoking the traverseFileSystem function using the new current directory path if it is a directory. The last line of the code invokes the  traverseFileSystem function on ‘..’ which is a simple way to reference the parent directory of the current working directory.

It is important to note that this solution uses the synchronous versions of some of the asynchronous methods used in previous examples in order to guarantee return values before proceeding with the code’s execution. This was done in the sake of simplicity in illustration of this solution and can be ported into an asynchronous version with little difficulty

5. Getting/setting file attributes

You want to get certain attributes of a given file such as whether or not it is a file or a directory, and you want to be able to set certain attributes such as the file’s name or the file’s permissions.

 var fs = require('fs');
 fs.stat('data.txt', function (err, stats) {
  if (err)
     throw err;
  if (stats.isFile()) {
      console.log('It\'s a file!');
  if (stats.isDirectory()) {
    console.log('It\'s a directory!');
  for (var i in stats) {
     if ('function' !== typeof stats[i])
     console.log(i + '\t= ' + stats[i]);
 fs.rename('data2.txt', 'data2_new.txt', function (err) {
  if (err)
    throw err;
 fs.chmod('data3.txt', '0777', function (err) {
   if (err)
      throw err;
   console.log('File permissions changed!');

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs.

The next line obtains information about a given file ‘data.txt’ using an asynchronous file stats call  stat(). On this same line we specify our anonymous callback function function (err, stats) which takes two parameters: any errors which occur as  err and a stats object of the given file as stats. Within the anonymous function, we first check for any potential errors and throw the error as an exception to be left to be caught by the calling process as if (err)  throw err;.

We then display on the console screen whether the given file is a file or a directory. After this, we step through each non-function member of the stats object and display what that member field’s name is and what value it contains (this will include detailed file information such as creation date, modified date, file size, etc).

The next section of the code executes the asynchronous rename() function to rename the file ‘data2.txt’ to ‘data2_new.txt’. In this same line, we are passing the anonymous callback function function (err) which, as before, passes any potential errors that might occur as its only parameter err.

We then use the same technique to check for any errors and then display ‘Renamed!’ if the file was successfully renamed. In the last section of the code we execute the asynchronous chmod() function to change the file permissions of our input file ‘data3.txt’ to ’0777′ (or all read-write-execute). In this same line, we are passing the anonymous callback function function (err) which, as before, passes any potential errors that might occur as its only parameter err. We then use the same technique to check for any errors and then display ‘File permissions changed!’ if the file permissions were successfully changed.

6. Watching a file for changes

You want to be notified of any changes that occur within a given directory either to the directory’s contents or directory itself.


This solution requires a special module called “inotify.” Assuming you have the node package manager installed, you can install inotify using: npm install inotify The code below must then reference the install path:

 var fs = require('fs');
 var Inotify = require('/usr/local/node/node_modules/inotify').Inotify;
 var inotify = new Inotify();
 var watcher = {
 path: '.',
 watch_for: Inotify.IN_OPEN | Inotify.IN_CLOSE,
 callback: function (event) {
 var file = event.name ? event.name : '';
 var mask = event.mask;
 if (file != '' && file.indexOf('.') !== 0) {
    if (mask & Inotify.IN_OPEN) {
    console.log(file + ' was opened ');
 else if (mask & Inotify.IN_CLOSE) {
    console.log(file + ' was closed ');

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs. We then include the inotify modulevar inotify = require(‘/usr/local/node/node_modules/inotify’).Inotify;  (note that this path should be whatever path you installed the inotify module to). On the next line, we are instantiating the inotify object new Inotify(); which we will use for watching for file changes.

The next few lines are all for defining our  watcher object with the following properties: path: ‘.’ (the path to the file we want to watch—in this case, we are watching the current working directory), watch_for: Inotify.IN_OPEN | Inotify.IN_CLOSE (specifying that we will only be firing change events when a file is opened or closed), and lastly, callback: function (event) {  … } (defines our callback function that will be fired whenever the above two events are emitted). In the first line of our callback, we are getting the filename from the event object var file = event.name ? event.name : ”;  (if the filename is null, we’ll set the variable to an empty string).

The next line is just to make a “shorthand” variable for the event type mask var mask = event.mask; .  The next conditional statement will filter out empty filenames and filenames that start with a “.” (which sometimes indicate a temporary file being used to write a file). The next couple of statements if (mask & Inotify.IN_OPEN) {  … } and then after  else if (mask & Inotify.IN_CLOSE) {  … }  will display whether there was a file opened or closed under the given directory location.

Lastly is a very important line of code where we add our watcher object that we just defined to the inotify object using inotify.addWatch(watcher); (note that without this very line, our watcher object is essentially useless).

For more info – https://nodejs.org/api/fs.html

Happy Coding Smile

Everything about Node.js (How-to-start)


Developer Sites







JavaScript resources

Node.js Modules


Happy Coding Smile

11 Tips to Improve AngularJS Performance


1. Minimize/Avoid Watchers

Usually, if your Angular app is slow, it means that you either have too many watcher, or those watchers are working harder then they should.

Angular uses dirty checking to keep track of all the changes in app. This means it will have to go through every watcher to check if they need to be updated (call the digest cycle). If one of the watcher is relied upon by another watcher, Angular would have to re-run the digest cycle again, to make sure that all of the changes has propagated. It will continue to do so, until all of the watchers have been updated and app has stabilized.

Even though running JavaScript in modern browsers is really fast, in Angular it is fairly easy to add so many watchers that you app will slow down to a crawl.

Keep in mind the following when implementing or refactoring an Angular app.

  1. Watches are set on:
    • $scope.$watch
    • {{ }} type bindings
    • Most directives (i.e. ng-show)
    • Scope variables scope: { bar: '='}
    • Filters {{ value | myFilter }}
    • ng-repeat
  2. Watchers (digest cycle) run on
    • User action (ng-click etc). Most built in directives will call $scope.apply upon completion which triggers the digest cycle.
    • ng-change
    • ng-model
    • $http events (so all ajax calls)
    • $q promises resolved
    • $timeout
    • $interval
    • Manual call to $scope.apply and $scope.digest

2. Avoid ng-repeat. If you have to use ng-repeat use infinite scrolling or pagination

This was the biggest win for our app. I am not going to go into too much details, but I found the article bellow to be extremely helpful.


In addition to infinite scroll, make sure to use track by when possible.https://docs.angularjs.org/api/ng/directive/ngRepeat#tracking-and-duplicates

For example a unique step id, is a good value to track by when doing an ng-repeat.

<li ng-repeat="Task in Tasks track by Task.Id></li>

3. Use Bind once when possible

Angular 1.3 added :: notation to allow one time binding. In summary, Angular will wait for a value to stabilize after it’s first series of digest cycles, and will use that value to render the DOM element. After that, Angular will remove the watcher forgetting about that binding.

If you are on pre 1.3 version of Angular you can use this library to achieve similar results:

4. Use $watchCollection instead of $watch (with a 3rd parameter)

$watch with only 2 parameters, is fast. However, Angular supports a 3rd parameter to this function, that can look like this: $watch('value', function(){}, true). The third parameter, tells Angular to perform deep checking, meaning to check every property of the object, which could be very expensive.

To address this performance issue, angular added $watchCollection('value', function(){}). $watchColleciton acts almost like $watch with a 3rd parameter, except it only checks the first layer of object’s properties, thus greatly improving the performance.

Official doc:

Helpful blog post:

5. Avoid repeated filters and cache data whenever possible

One time binding does not seem to play well with filters. There seems to be work arounds to make it work, but I think it’s cleaner and more intuitive to simply assign the needed value to a variable (or set it as a property on an object, if you are dealing with a lot of variables).

For example, instead of:

{{'DESCRIPTION' | translate }}

You can do:
– In JavaScript $scope.description: $translate.instant('DESCRIPTION')
– In HTML {{::description}}

Or instead of: {{step.time_modified | timeFormatFilter}}

  • In JavaScript

var timeFormatFilter = $filter(‘timeFormatFilter’);

step.time_modified = timeFormatFilter(step.time_modified);

  • In HTML {{::Path.time_modified}}

6. Debounce ng-model

If you know there is going to be a lot of changes coming from an ng-model, you can de-bounce the input.

For example if you have a search input like Google, you can de-bounce it by setting the following ng-model option: ng-model-options="{ debounce: 250 }.

This will ensure that the digest cycle due to the changes in this input model will get triggered no more then once per 250ms .


7. Use ng-if instead of ng-show (but confirm that ng-if is actually better for your use case)

ng-show will render an element, and use display:none to hide it,
ng-if will actually removes the element from DOM, and will re-create it, if it’s needed.

You may need ng-show for an elements that toggles on an off often, but for 95% of the time, ng-if is a better way to go.

8. Use console.time to benchmark your functions

console.time is a great API, and I found it particularly helpful when debugging issues with Angular performance. I placed a number of those calls through out my code, to help me confirm that my re-factoring was in fact improving the performance.


The API looks as such:


//Some code


And here is a simple example:




}, 100);

//In console $: TimerName: 100.324ms

Note: If console.time is not precise enough for your needs, you can get a more accurate reading using performance.now(). You will have to do your own math, if you choose to take this path.


totalTime = 0; count = 0;

var someFunction = function() {

var thisRunStartTime = performance.now();


// some code

// some more code

totalTime += performance.now() – thisRunStartTime;


console.log(“Average time: ” + totalTime/count);

9. Use native JavaScript or Lodash for slow functions

Our app was already using lodash, so there was no overhead for me to use it in my optimization. If lodash was not include, I would probably try to re-write everything in native JavaScript.

In my tests I got a significant performance boost by simply re-writing some of the basic logic with lodash, instead of relying on built-in Angular methods (which have to account for much more generic use cases).

Maintainer of Lodash John-David Dalton is also a co-creator of https://jsperf.com/, and he is all about the performance. So I trust him and his library when it comes to speed.

10. Use Batarang to benchmark your watchers

Batarang is a great tool from the Angular team, and it was very helpful in my debugging efforts. It has a lot of useful features, but the one that was the most relevant to this use-case is the performance tab.


Make sure to get the stable version, which seems to work for the majority of users.

Watch this video to get more insight into the Batarang.

11. Use Chrome Timeline and Profiler to identify performance bottlenecks

I like to think of myself as a Chrome Dev Tools power user. But it’s not often that I get a to use the Timeline and Profiler views. In this project, both were extremely helpful.

Pro Tip: If you use console.time API (see tip #8), the time period will get highlighted on your timeline snapshot. So you can examine the exact time period that you care about the most.


The timeline view, and the magic 60fps line is crucial. When I started on our project, the app was rendering full steam for 15 seconds or more, becoming almost completely unresponsive to the user.


After performance optimization, the app now fully renders in less then 2 seconds (note that the time scale is different), allowing users to freely interact with the user interface after a relatively short delay.


It is clear from looking at the image that the app could be further optimized. But even as is, I am very happy with the improvements to the user experience.

To get more experience with Timeline view, check out these web audits by Paul Irish:


Finally, I wanted to mentioned the Profiling tab in Chrome Dev tools, and the JavaScript CPU profiler in particular. It has 3 views:

1. Chart view is similar to the timeline, but it makes it a bit easier to jump to the source code of the function of interest.


2. Heavy (Bottom up view)
This view identifies heavy user functions, and shows you the reverse call stack to help pinpoint origination of the function. Note how $digest comes before the $apply, indicating the reverse order.


3. Tree (Top Down)
Exposes the functions from which the heavy consumption originated, and then you can drill down to find the offending function.

Also note the yellow triangle with a “!”, if you however over it, it will identify a potential optimization problem.



Thanks to Alex Kras for Sharing wonderful article across developers.

Happy Coding Smile

ionic/angular: Use The Android And iOS Camera With Ionic Framework



Most smart phones on the market have at least one camera if not two.  You may want to leverage these cameras to make the next Instagram or SnapChat type application.  Lucky for us, the native Android and iOS camera can be easily accessed using Ionic Framework and the AngularJS extension set, ngCordova.

Thanks for Nick Raboy for wonderful article.

Happy Hybrid App Development…

ionic/angular: Implement A Barcode Scanner Using Ionic Framework



More specifically I needed to scan quick response (QR) codes.  After doing some searching I found that ngCordova had an extension for the Apache Cordova plugin BarcodeScanner which has the ability to scan barcodes in the following formats:

  • QR Code
  • Data Matrix
  • UPC E
  • UPC A
  • EAN 8
  • EAN 13
  • Code 128
  • Code 39
  • ITF

Pretty much all the formats anyone would ever need.  The plugin itself makes use of the very popular ZXing library.

Thanks to Nick Raboy for wonderful article.

Happy Android Development 🙂

ionic/angular: Create, Delete, And Search Contacts In Ionic Framework



When you make an app or service, you may find your self wanting to strengthen the user experience by connecting with friends in some fashion.  Applications like Facebook and Twitter allow you to search your contact book for friends that are already using their service.  If your friend isn’t using the service, you have the option to invite them.

Using native Android and iOS code could make this process very painful for the developer as it is lengthy and difficult.  Lucky for us, we are using Apache Cordova with Ionic Framework and there is a plugin for us that takes all the pain away.

The following steps will show you how to create, delete, and find all device contacts in your Ionic Framework project.
Thanks to Nick Raboy for wonderful article.
Happy Android Development 🙂

ionic/angular: Syncing Data With Dropbox Using Ionic Framework



Storing or syncing data remotely is often a need in modern apps.  This generation is all about the cloud and how to be a part of it.  IonicFramework is a great way to make hybrid cross platform mobile Android and iOS applications, but how about sharing data between them?  Dropbox is one of a few cloud storage services that happens to have great APIs and documentation.

The following won’t necessarily show you the best way for syncing data in IonicFramework using Dropbox’s Datastore API, but it will show you how I did it with success.

Thanks to Nick Raboy.

Happy Android Hybrid App Development 🙂

Angular: How to set IsActive on tab or any other bootstrap controlsive

One way of doing this would be by using ngClass directive and the $location service. In your template you could do:


where isActive would be a function in a scope defined like this:

myApp.controller('MyCtrl', function($scope, $location) {
    $scope.isActive = function(route) {
        return route === $location.path();

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/KzAfG/

Repeating ng-class="{active:isActive('/dashboard')}" on each navigation tab might be tedious (if you’ve got many tabs) so this logic might be a candidate for a very simple directive.

Happy coding..:)

AngularJS – All about building Custom Filters

Today, we will build our own custom AngularJS filters. We’ll start simple and build a couple filters that manipulate numbers and strings, then we’ll build a filter that manipulate an entire data set. Finally, in our previous article where we discussed the built in AngularJS filters, Pierre-Adrien asked how we could use the built in Angular currency filter to display the currency denomination after the amount (i.e. 9.99$ instead of $9.99) as is common in some places of the world. Unfortunately, the built-in currency filter does not support this functionality, so we’ll build our own that does!

Read original article with demo –


Happy Coding … 🙂

Using Resolve In AngularJS Routes

Found really nice article from “Ode to Code by Scott Allen”

A resolve is a property you can attach to a route in both ngRoute and the more robust UI router. A resolve contains one or more promises that must resolve successfully before the route will change. This means you can wait for data to become available before showing a view, and simplify the initialization of the model inside a controller because the initial data is given to the controller instead of the controller needing to go out and fetch the data.

As an example, let’s use the following simple service which uses $q to simulate the async work required to fetch some data.

app.factory("messageService", function($q){
    return {
        getMessage: function(){
            return $q.when("Hello World!");

And now the routing configuration that will use the service in a resolve.

    .when("/news", {
        templateUrl: "newsView.html",
        controller: "newsController",
        resolve: {
            message: function(messageService){
                return messageService.getMessage();

Resolve is a property on the routing configuration, and each property on resolve can be an injectable function (meaning it can ask for service dependencies). The function should return a promise.

When the promise completes successfully, the resolve property (message in this scenario) is available to inject into a controller function. In other words, all a controller needs to do to grab data gathered during resolve is to ask for the data using the same name as the resolve property (message).

app.controller("newsController", function (message) {
    $scope.message = message;

You can work with multiple resolve properties. As an example, let’s introduce a 2nd service. Unlike the messageService, this service is a little bit slow.

app.factory("greetingService", function($q, $timeout){
   return {
       getGreeting: function(){
           var deferred = $q.defer();
           return deferred.promise;

Now the resolve in the routing configuration has two promise producing functions.

.when("/news", {
    templateUrl: "newsView.html",
    controller: "newsController",
    resolve: {
        message: function(messageService){
            return messageService.getMessage();
        greeting: function(greetingService){
            return greetingService.getGreeting();

And the associated controller can ask for both message and greeting.

app.controller("newsController", function ($scope, message, greeting) {
    $scope.message = message;
    $scope.greeting = greeting;

Composing Resolve

Although there are benefits to moving code out of a controller, there are also drawbacks to having code inside the route definitions. For controllers that require a complicated setup I like to use a small service dedicated to providing resolve features for a controller. The service relies heavily on promise composition and might look like the following.

app.factory("newsControllerInitialData", function(messageService, greetingService, $q) {
    return function() {
        var message = messageService.getMessage();
        var greeting = greetingService.getGreeting();
        return $q.all([message, greeting]).then(function(results){
            return {
                message: results[0],
                greeting: results[1]

Not only is the code inside a service easier to test than the code inside a route definition, but the route definitions are also easier to read.

.when("/news", {
    templateUrl: "newsView.html",
    controller: "newsController",
    resolve: {
        initialData: function(newsControllerInitialData){
            return newsControllerInitialData();

And the controller is also easy.

app.controller("newsController", function ($scope, initialData) {
    $scope.message = initialData.message;
    $scope.greeting = initialData.greeting;

One of the keys to all of this working is $q.all, which is a beautiful way to compose promises and run requests in parallel.


Happy Coding 🙂

angular- Stop event propogation

simple angularjs way –

ng-click="UpdateResponderStatus(item, status.id); $event.stopPropagation();"

directive way –

.directive('stopEvent', function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
element.bind(attr.stopEvent, function (e) {

that could be used this way:

Happy Coding.. 🙂

Error Logging with Elmah & JSNLog : Javascript exception logger to log exceptions on server side log.

Since longtime, I was logging server side exceptions using log4net in all my asp.net web sites. Now I was using “console.log” extensively for debug purpose and logging purpose. BUT there was not known method to me at least which can log the client side errors & info etc. to same server side logging engine, until I learnt JSNLog…. 

Summary: What is jsnlog anyways ?

JSNLog lets you insert loggers in your client side JavaScript, configure them in your web.config, and store their messages in your server side logs.

Why there is a need ?

Using your server side logging package, such as Log4Net, NLog or Elmah, with loggers configured via web.config,

catch (Exception e)
    ILog log = LogManager.GetLogger("serverlogger");


but how can we merge client side javascript try-catch exceptions to these server side logging engines ?

try { .... } catch(err) { ???? }

But what about exceptions in your JavaScript code?

JSNLog will pass the JavaScript exception log message with its stack trace on to your server side logging package, so it winds up in your server side logs. You can log extra information, such as the values of variables.


    // Log the exception, complete with stack trace
    JL("jsLogger").fatalException({ "msg": "something went wrong!", "variable1": variable1, ... }, e);

 or we can always write master function using window.onerror () in javascript , like – 

window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
        "msg": "something went wrong!", 
        "errorMsg": errorMsg, "url": url, 
        "line number": lineNumber, "column": column
    }, errorObj);
    return false;


  • Extensive documentation. Easy to install.
  • No need to pay fees to a third party logging service.
  • JavaScript log messages go into the same logs as your server side log messages.
  • Or send JavaScript log messages to the browser console.
  • Uses a tiny JavaScript library that can be loaded as an AMD module or with a simple script tag, or as part of abundle.
  • Request ids correlate JavaScript log messages and server side log messages generated by the same user session.
  • Configure JavaScript loggers in your web.config.
  • Many filtering options to prevent flooding your server with JavaScript log messages.
  • Option to send JavaScript log messages in batches of 2 or more for greater efficiency.
  • Logs JSON objects as well as strings.

Vital Stats

Key concepts

  • Insert loggers in your client side JavaScript, using jsnlog.js (2kb min+gz).
  • Those loggers send your log messages to the JSNLog server side component.
  • This logs the messages in your server side log, using your server side logging package. Supports Log4Net, NLog, Elmah, Common.Logging.


(This is how your JSNLog + Elmah interface will look like )


Now, let’s talk about some installation process and configuration etc 


Install JSNLog plus configuration for your logging package

The NuGet packages below install JSNLog itself, plus the configuration needed for it to work with your specific logging package.

  1. Load your solution in Visual Studio, and open the Package Manager Console: Tools | Library Package Manager |Package Manager Console.
  2. Enter the NuGet package at the PM> prompt to install JSNLog plus configuration for your logging package:
Logging Package NuGet package
Log4Net Install-Package JSNLog.Log4Net
NLog Install-Package JSNLog.NLog
Elmah Install-Package JSNLog.Elmah
Serilog Install-Package JSNLog.Serilog
Common.Logging Install-Package JSNLog.CommonLogging

If your logging package is not listed here, install the version for Common.Logging and then install a Common.Loggingadapter for your logging package.


STEP – 2


Add JSNLog to your pages

Call JSNLog’s Configure method in your pages, before any script tags that load JavaScript that use JSNLog loggers.

  • For Razor (MVC3+), use:
    ... your <script> tags

    Your _Layout.cshtml or _Layout.vbhtml would probably be a good place for this.

  • For WebForms, use:
    <%= JSNLog.JavascriptLogging.Configure() %>
    ... your <script> tags

    Your master page would probably be a good place for this.


That’s It friends — Now let’s start logging 

function onButton2Click() {
try {
    // ReferenceError: xyz is not defined
} catch (e) {
    // Log the exception
    JL().fatalException("something went wrong!", e);
    // Rethrow the exception, so the browser 
    // doesn't forget about this error situaion.
    throw e


You may do some web.config settings change if you may want to – 


        productionLibraryPath="string" >

Learning kit – 

Here are the few nice articles which I liked when I was learning this – 

1. obviously their own documentation is more than enough material 

Please refer: http://jsnlog.com/Documentation/GetStartedLogging

2. EVeryone like video tutorials 🙂 

Please refer: http://vimeo.com/channels/jsnlog/videos

Nugets are here too :  https://www.nuget.org/packages/JSNLog.Elmah/

Elmah Resources too : https://code.google.com/p/elmah/

Scott Hanselman’s article on Elmah –                                        http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx

there are many things to cover on these two logger engines like Elmah & jsnLog. Please feel free to send me if you find really nice articles too. 


I hope this helps begginers like me… 🙂 Happy coding friends… 




The Many Ways To Use ngClass

AngularJS provides some great features to help us create interactive applications. They provide things called directives in order to change the DOM and attach specific Angular behaviors to an element we specify.

Today we’ll be looking at the ngClass directive. This directive let’s us do awesome things like:

  • Add/Remove classes based on Angular variables
  • Add/Remove classes based on evaluated expressions
  • Bind single or multiple classes based on dynamic data

Here’s a quick example of some fun stuff you can do by dynamically adding classes.

ngClass Using String Syntax

This is the simplest way to use ngClass. You can just add an Angular variable to ng-class and that is the class that will be used for that element.

<!-- whatever is typed into this input will be used as the class for the div below -->
<input type="text" ng-model="textType">

<!-- the class will be whatever is typed into the input box above -->
<div ng-class="textType">Look! I'm Words!</div>

ngClass Using Evaluated Expression

A more advanced method of using ngClass (and one that you will probably use the most) is to evaluate an expression. The way this works is that if a variable or expression evaluates to true, you can apply a certain class. If not, then the class won’t be applied.

<!-- input box to toggle a variable to true or false -->
<input type="checkbox" ng-model="awesome"> Are You Awesome?
<input type="checkbox" ng-model="giant"> Are You a Giant?

<!-- add the class 'text-success' if the variable 'awesome' is true -->
<div ng-class="{ 'text-success': awesome, 'text-large': giant }">


ngClass Using Array Syntax

This is similar to the string syntax method except you are able to apply multiple classes.

<!-- both input boxes below will be classes for the div --> <input type="text" ng-model="styleOne"> <input type="text" ng-model="styleTwo"> <!-- this div will take on both classes from above --> <div ng-class="[styleOne, styleTwo]">Look! I'm Words!</div>


ngClass Using the Ternary Operator

The ternary operator allows us to use shorthand to specify two different classes, one if an expression is true and one for false. Here is the basic syntax for the ternary operator:

ng-class="$even ? 'even-row' : 'odd-row'">

And an explanation example:

ng-class="$variableToEvaluate ? 'class-if-true' : 'class-if-false'">
ngClass as an Attribute

<!-- example with string syntax -->
<!-- use the type variable as a class -->
<div class="item" ng-class="type">Stuff Goes Here</div>

<!-- example with string syntax -->
<!-- use the styleOne and styleTwo variables as classes -->
<div class="item" ng-class="[styleOne, styleTwo]">Stuff Goes Here</div>

<!-- example with evaluated data -->
<!-- add the text-error class if wrong is true -->
<div class="item" ng-class="{ 'text-error': wrong }">Stuff Goes Here</div>

Happy Coding Smile

angular-strap : $injector:moduler using angular-strap?

 Problem : 



I am trying to get going with angular-strap directives, but encountering a module initialization error with the simplest setup. I have double checked a zillion times but can’t see exactly what I might be missing.

Here is a plunker link: http://plnkr.co/edit/H1VrF63GeSQWLXHDVIW7

The error I get is:

Error: [$injector:modulerr] Failed to instantiate module mgcrea.ngStrap due to:
Error: [$injector:nomod] Module 'mgcrea.ngStrap' is not available! You either misspe...  <omitted>...1) 

I read this response, but it didn’t answer my question as I am not using ngSanitize or routes. This is as simple as it gets.


Your plunk needs angular-animate, which angular-strap depends on.


<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular-animate.min.js"></script>

How to set value property in angularjs ng-options?



ngOptions(optional) – {comprehension_expression=} – in one of the following forms:

for array data sources:
label for value in array
select as label for value in array
label group by group for value in array
select as label group by group for value in array
for object data sources:
label for (key , value) in object
select as label for (key , value) in object
label group by group for (key, value) in object
select as label group by group for (key, value) in object

In your case, it should be

array = [{ "value": 1, "text": "1st" }, { "value": 2, "text": "2nd" }];

<select ng-options="obj.value as obj.text for obj in array"></select>

required field Label–Angularjs Directive

So I thought to make some kind of custom <label> where I have mark showing that this field is required along with label text….

In angular, we can take advantage of making directives for this kind of custom control, so I did something like below –


<required-label label=”First Name”></required-label>

app.JS  (Angular Directive)

appRoot.directive(‘requiredLabel’, function () {
    return {
        restrict: ‘E’,
        replace: false,
        scope: {
            name: ‘@’
        template: “<label popover=’Required Input’ popover-trigger=’mouseenter’ >{{Text}}&nbsp;<i class=’icon ion-ios7-star red’></i>&nbsp;”,
        link: function (scope, element, attrs) {
            scope.Text = attrs[‘label’];

Happy CodingSmile