Difference between Angular 1 VS Angular 2

Angular 1 vs angular 2 -AngularJs

Last month Angular 2.0 released by Ng-team, and within a month it’s created a buzz in AngularJs community. Angular 2 is using Hierarchical Dependency Injection system which is major performance booster. Angular 2 implements unidirectional tree based change detection which again increases performance. As per ng-conf meetup,
Angular 2 is 5 times faster as compared to Angular 1. Angular 2 will be a huge learning curve for developers. It is written entirely in Typescript and meets the ES6 specification. And it’s not an update for Angular 1.x. As it’s rewritten and includes breaking changes. So the best way to learn is to compare with Angular 1.x and find out what’s new in Angular 2. In this post, I am going to show differences between Angular 1.x and Angular 2. Let’s begin….




Difference between Angular 1.x Vs Angular 2

1). Angular 2 is mobile oriented & better in performance. 

Angular 1.x was not built with mobile support in mind, where Angular 2 is mobile oriented. Angular 2 is using Hierarchical Dependency Injection system which is major performance booster. Angular 2 implements unidirectional tree based change detection which again increases performance. As per ng-conf meetup, angular 2 is 5 times faster as compared to angular 1.

 

2). Angular 2 provides more choice for languages.

Angular 2 provides more choice for languages. You can use any of the languages from ES5, ES6, TypeScript or Dart to write Angular 2 code. Where, Angular 1.x has ES5, ES6, and Dart. Using of TypeScript is a great step as TypeScript is an awesome way to write JavaScript.

3). Angular 2 implements web standards like components.

Angular 2 implements web standards like components, and it provides better performance than Angular 1.

Difference-betwee-Angular-1-vs-Angular-2-component

4). AngularJS 2.0 is not easy to setup as AngularJS 1.x.

AngularJS 1.x is easy to setup. All you need to do is to add reference of library and you are good to go. Where AngularJS 2 is dependent on other libraries and it requires some efforts to set up it.
[UPDATE: Angular Team heard this and they introduced Angular CLI to create AngularJS 2 applications.]

5). Angular 1.x controllers and $scope are gone.

Angular 1.x controllers and $scope are gone. We can say that controllers are replaced with “Components” in Angular 2. Angular 2 is component based. Angular 2 is using zone.js to detect changes.

  • Angular 1.x Controller
    var myApp = angular
    .module("myModule", [])
    .controller("productController", function($scope) {
             var prods = { name: "Prod1", quantity: 1 };
             $scope.products = prods;
    });

     

  • Angular 2 Components using TypeScript
import { Component } from '@angular/core';

@Component({
    selector: 'prodsdata',
    template: '<h3>{{prods.name}}</h3>'
})

export class ProductComponent {
    prods = {name: 'Prod1', quantity: 1 };
}

Note: there is a class with ‘export’ keyword, @Componentannotation (that’s also new in Angular 2). The @Componentannotation adds the metadata to the class.

Difference-betwee-Angular-1-vs-angular2

 

Read also: What is the Difference Between String and StringBuilder in C#.




6). Different ways to define local variables.

In Angular 2, local variables are defined using Hash(#) prefix.

<div *ngFor="#technicalDiary of technicalDiries">

7). Structural directives syntax is changed.

In Angular 2, Structural directives syntax is changed. ng-repeat is replaced with *ngFor.
Angular 1.x structural directives:

<ul>
   <li ng-repeat="technology in technologies">
     {{technology.name}}
   </li>
</ul>

Angular 2 structural directives:

<ul>
  <li *ngFor="#technology of technologies">
    {{technology.name}}
  </li>
</ul>

Note : Asterisk(*) sign is used as prefix for structural directives, is replaced with and camelCase syntax is used.

UPDATE: In AngularJS 2 version “2.0.0-beta.17”, there is a small change with respect to *ngFor instead of “#” use “let”.

8). Angular 2 uses camelCase syntax for built-in directives.

Angular 2 uses camelCase syntax for built-in directives. For example, ng-class is now ngClass and ng-model is now ngModel.

9). Angular 2, directly uses the valid HTML DOM element properties and events.

One of the major change in Angular 2 is, that it directly uses the valid HTML DOM element properties and events. Due to this, many of the available built-in directives in Angular 1.x are now no longer required. Like ng-href, ng-src, ng-show and ng-hide. Angular 2 uses href, src and hiddenproperties to get the same output. And same goes with event based directives like ng-click and ng-blur.

<button ng-click="doSomething()">

And in Angular 2, take the HTML event and wrap it with parentheses.

<button (click)="doSomething()">

10). One-way data binding directive replaced with [property].

In Angular 1.x, ng-bind is used for one-way data binding, but with Angular 2 it is replaced with [property], where ‘property’ is valid HTML DOM element property.
Angular 1.x, one-way data binding

<input ng-bind="technology.name"></input>

Angular 2, one-way data binding is achieved via wrapping the properties with square brackets.

<button (click)="doSomething()">

11). Two-way data binding: ng-model replaced with [(ngModel)]

In Angular 1.x, ng-model is used for two-way data binding, but with Angular 2 it is replaced with [(ngModel)].
Angular 1.x, two-way data binding,

<input ng-model="technology.name"></input>

In Angular 2,

<input [(ngModel)]="technology.name"></input>

 12). Way of Bootstrapping Angular Application is changed:

  • Angular 1.x has 2 ways to bootstrap angular. One using ng-appattribute and other via code.
  1. <script>
       angular.element(document).ready(function() {
          angular.bootstrap(document, ['myApp']);
       });
    </script>

 

In Angular 2, say goodbye to ng-app. The only way to bootstrap angular is via code.

import { bootstrap } from 'angular2/platform/browser';
import { ProductComponent } from './product.component';

bootstrap(ProductComponent);

The bootstrap function is used and it takes starting component which is also parent component of your angular application.

13). Ways of Dependency Injection is Changed- syntax changed.

One of the advantages of Angular is Dependency Injection. With Angular 2 DI is there but now there is a different way to inject dependencies. As everything is ‘class’ in Angular, so DI is achieving via constructors.

In Angular 1.x,

var myApp = angular
   .module("myModule", [])
   .controller("productController", function($scope, $http) {
        var prods = { name: "Prod1", quantity: 1 };
        $scope.products = prods;
    });

In Angular 2,

import { Injectable } from 'angular2/core';

@Injectable()

export class TechnologyService {
    constructor(private _http: Http) { }
    getTechnologies() {
        return [new technology(1, 'Angular'),
            new technology(2, 'jQuery',
            new technology(3, 'Node'),
            new technology(4, 'Knockout')
        ];
    }
}

Note: @Injectable() is added to service class. It is similar to Angular 1.x $inject used for DI.

14). Way of routing is Changed- syntax changed.

In Angular 1.x, we use $routeProvider.when() to configuring routing. Where in Angular 2, @RouteConfig{(...}) is used. ng-view present in Angular 1.x is replaced with <router-outlet>
In Angular 1.x,

var app = angular
        .module("MyModule", ["ngRoute"])
        .config(function ($routeProvider) {
            $routeProvider
            .when("/home", { templateUrl: "home.html", controller: "homeController" })
            .when("/technology", { templateUrl: "technology.html", controller: "technologyController" })
        })
       .controller("homeController", function ($scope) {
            $scope.message = "Home Page";
        })   
       .controller("technologyController", function ($scope) {
             $scope.technologies = ["ASP.NET", "jQuery", "AngularJS", "JavaScript"];
       })

In Angular 2,

import { Component } from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
import { TechnologyComponent } from './technology/technology.component';
import { TechnologyService } from './Technology/Technology.service';
 
@Component({
  selector: 'my-app',
  templateUrl: 'app/app.component.html',
  directives: [ROUTER_DIRECTIVES],
  providers: [
    ROUTER_PROVIDERS,
    TechnologyService
  ]
})
@RouteConfig([
  { path: '/home', name: 'Home', component: HomeComponent, useAsDefault: true },
  { path: '/technology', name: 'Technology', component: TechnologyComponent },
])

export class AppComponent { }
Routing is a separate module that’s why need to import it. And 2 more configurations needs to be to make routing work, one is adding[ROUTER_DIRECTIVES] as directive and other is to add ROUTER_DIRECTIVES in providers list. And in HTML page,
<ul>
  <li><a [routerLink]="['Home']" href="">Home</a></li>
  <li><a [routerLink]="['Technology']" href="">Technology</a></li>
</ul>
ng-href is also replaced by [routerLink]

Conclusion:

Although angular 2 is still in beta, I consider this as a major upgrade from Angular 1. Angular 2 has very powerful routes. The Angular 2 Router will only load components when it absolutely needs them. Kind of partial loading which is a great feature I think. Angular 2 is 5 times faster as compared to Angular 1.

It certainly requires some efforts to migrate from Angular 1 to Angular 2, but it is in the right direction. Things are looking better and more inline with HTML. It is still in beta but eagerly waiting for the final release.

That’s all I can think of. I know there are many points which can be included in this list. If you come across any please mention in comments box section or send it on twitter/facebook. I will appreciate if somebody wants to add something which I have missed. Keep visiting for updates and share this in your network. 🙂

 

S Sharif

Founder of Technical Diary. Software engineer and passionate about technologies to learn and share. Crazy about best practices and new technology. I have worked in C#,ASP.NET MVC, HTML5, AngularJs SharePoint and SQL Server. I always try to keep myself updated and learn and implement new technologies. You can connect me on Twitter Facebook LinkedIn.

You may also like...

24 Responses

  1. Jeff Jin says:

    Great post. Just spot a typo under “10). One-way data binding directive replaced with [property]” for angular 2:

    should be

  2. Ankul Chaudhry says:

    Awesome article Thanks

  3. Kunal Rai says:

    Hi
    I am Kunal Rai from India. I like your post thanks for the theory

  4. Liam says:

    Hello,
    I am Liam from Netherland. I really liked your this article and your website. I also want to write some post.
    Please allow me to submit it.

  5. SotheaRio says:

    Thank for post this article 🙂

  6. Pawan Gupta says:

    I am new to AngularJS and as described above there both versions are very different. Request you to please suggest that from which version should I start either Angular 1.x or Angular 2.x ?

  7. corburterilio says:

    Its excellent as your other blog posts : D, thankyou for posting.

  8. Sheri says:

    This content is really interesting. I have bookmarked it.
    Do you allow guest post on your site ? I can provide high quality articles for you.
    Let me know.

  9. Janis says:

    This site is really interesting. I have bookmarked it.

    Do you allow guest posting on your page ? I can write high quality articles for you.
    Let me know.

  10. Daniel88 says:

    I see a lot of interesting articles here. Your blog can go viral easily,
    you need some initial traffic only. How to get initial traffic?

    Search for: masitsu’s viral method

  11. Johannah says:

    It’s spooky how clever some ppl are. Thaskn!

  12. Donyell says:

    Learning a ton from these neat arlitces.

  13. Sanne says:

    It’s a real pluraese to find someone who can think like that

  14. Cathy says:

    Good to see real expertise on display. Your cotirtbunion is most welcome.

  15. Eric says:

    Angular1 and Angular2 are quite different. Angular2 is actually a complete rewrite not an improved Angular2. Between Angular1 and Angular2 there was also Angular.dart which already was a complete rewrite and in retrospect can be seen as a prototype for Angular2. Just to make it obvious how much difference is between Angular1 and Angular2.

  16. Anoop K says:

    What is TypeScript?? Is it same like as ES6 specification?

    • S Sharif says:

      TypeScript is a free and open source programming language developed and maintained by Microsoft.It is a superset of JavaScript which primarily provides optional static typing and class-based object-oriented programming to the language. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.
      To get an idea of what I mean, click here.

  17. Samuel D. says:

    We are about to start a new project with Angular. With no release date announced, we are kind of confused about whether to wait 2.0 release date or go ahead with 1.4 ?

    Please suggest.

    • S Sharif says:

      Originally Google said they would support AngularJS 1.x for approx one year after the late-2015 release of 2.0. (so for the entire 2016), and they received a harsh reaction from the community.

      Then, they changed their tune, saying that they will support version 1 as long as there is a high demand. This demand will be measured somehow by how well the community adopts version 2 as opposed to 1. (let’s assume another year of updates, 2017)

      When it comes to job posts AngularJS is still HUGE from what I’ve seen, which shows that companies are still investing heavily in 1.x. for new projects.

      So, let’s say Google will abandon the project for 2018. AngularJS is still open source (not like Windows XP), so there’s an opportunity for others to pick up development from where Google left off. Even for version 1.4, Google states that:”This Angular version is the first to be run by a much broader community-oriented team, including many people from outside of the Google Angular team…”

      So will Angular 1.x. By the time 2.5 years have past, version 2.x will be more stable and the migration path will be proven and tested.

  18. M J S Prasad says:

    Great article

  1. July 3, 2016

    […] the full article, click here. @TechnicalDiary: “Difference between AngularJs 1 VS AngularJs 2: Angular 2 is still in beta […]

Leave a Reply

Your email address will not be published. Required fields are marked *