Codementor Events

Migrating from Angular 1.x to Angular 2: Upgrade Strategies

Published Sep 20, 2016Last updated Aug 16, 2017

Angular 2.0 has just been officially released!

As of this writing, Angular 2 is in its final release version and sooner or later, all applications built in Angular 1.x will be required to be migrated to version 2 in order to be in sync with the latest Angular technology.

The new Angular framework is a complete re-write of the existing Angular 1.x framework and will not be backward-compatible with the applications built in previous versions.

What could be the reason behind re-writing an entire framework that’s backward incompatible? It’s not that the Angular team had no work to do and that they are trying to “reinvent the wheel” after writing Angular 1.x—I’d say, if Angular 1.x is good then Angular 2 is an improvement!

The following are the advanced features which make Angular 2 better than previous versions.

Better performance

Angular 1.x’s data binding concepts have lots of complaints and performance dissatisfaction due to delays and bottlenecks. In Angular 2,  improvements in data binding techniques increased overall app performance and operating speed at data exchange.

Adequate support for mobile or smartphones

Let’s face it, Angular 1.x  were never built with adequate mobile or smartphone support. Though some support issues are addressed when using Ionic (i.e. Advanced HTML5 Hybrid Mobile App Framework), issues with performance and user experience still didn’t attract many mobile users. Therefore, the necessity to update Angular with better performance over its predecessor frameworks is inevitable. Angular 2 is designed with an objective that will make it robust enough to be able to adapt to future mobile and smartphone technology.

The future of web development

Angular 2.0 is implemented in TypeScript (a language which is the superset of JavaScript) and ES2015/ES6 (i.e. main ECMAScript version). TypeScript is a very robust language maintained by Microsoft. Its biggest advantage is that it’s less susceptible to run-time errors due to the presence of types in the language. Angular 2.0 code is written in TypeScript which ultimately gets compiled into the JavaScript code.

This combination has all the encouraging features which are capable enough to meet not only the day-to-day web app development expectations but also the future challenges in web development.

Straightforward and easier to learn

Based on blogs and articles from Angular developers, I can conclude that Angular 2 is easier to learn compared to 1.x. It would typically take a week for developers to learn Angular 1.x. However, Angular 2 is very straightforward; developers migrating to it could kickstart their work on this framework within three to four days. But migrating from Angular 1 to 2 could also be harder for developers as it could mean abandoning all their previous Angular coding knowledge in order to catch up and stay updated with Angular 2.

Let’s take a look at the following examples on Angular 2 for novices. Angular 2 has the three core concepts: Components, Dependency Injection, and Bindings.

Those who are familiar with Angular know this very well—Angular 1.x uses directives, controllers, and scope for building an application. This whole concept has now been lumped into Components in Angular 2. In the following example, app/app-component.ts, we are first importing Component from @angular/core package. Then we will use the @Component decorator which has selector, templateUrl, and styleUrls. The selector defines the tag that loads the app in the body section of the index.html as shown below. The templateUrl defines the path where the actual HTML template file is located. The styleUrls defines the path where the stylesheet CSS file is located which styles the text and the element on the template. Lastly, we are exporting the AppComponent class, which is used as a controller class.

app/app-component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-angular2-app',
  templateUrl: 'resource/template.html',
  styleUrls: ['assets/styles.css'] 
})

export class AppComponent { 
  heading = "Welcome to Angular 2.0 framework";
  paragraph = "Hello World!";
}

template.html: It is called in Component as templateUrl.

<h3>{{heading}}</h3>
<p>{{paragraph}}</p>

Index.html : This is the main HTML ride that renders and starts the app. It has the selector my-first-angular2-app, which is present in the body section as shown below.

<html>
<head>
<title>Angular 2.0 App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/styles.css">
<! -- 1. Load libraries --><!-- Poly-fills for the older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<! -- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
      System.import('app').catch(
    		  function(err){ 
    			  console.error(err); 
    			  }
    		  );
</script>

Output

The following is the output for the Angular 2.0 app above.

angular 2

Did you find anything difficult about the Angular 2 TypeScript coding so far? Since Angular 2 is not backward compatible, all existing apps built in Angular 1.x are required to be migrated to version 2 because the Angular team will now be focusing more support on latest versions and previous ones will have less and less support in the future.

Migrating from Angular 1 to Angular 2

Here are some ways you can migrate from Angular 1.x to Angular 2.

Apps that don’t need to be migrated

Let’s look at the easiest approach for now. We all know that Internet Explorer 10 still has users even though the market has the latest Microsoft Edge browser available. In a similar way, applications that are close to the end of their lifecycle but are operating well on Angular 1.x  are not at all required to migrate to Angular 2.0. Any effort to update or migrate an app that’s about to get terminated is a will just be a waste of effort, and by then, AngularJS 1.x will not be deprecated officially

Rebuild in Angular 2

I would say that this is the cleanest approach—rebuilding the complete application from scratch in Angular 2 by knocking out the Angular 1.x application. But as we all know too well, developing any application from scratch incurs both cost and the stability risks. Keeping both the factors in mind, the company or app owner should decide either to rebuild the application from scratch in Angular 2.0 or use the ngForward or ngUpgrade approach, which I will explain next.

Use the ngForward approach

In the ngForward approach, we are not actually upgrading existing Angular 1.x applications—we are creating an environment where these 1.x applications will behave like Angular 2 applications. In other words, we can gradually rewrite our Angular 1.x app to work like an Angular 2 app. We can then further augment new Angular 2 features to this 1.x application on the top of the existing app.

The following steps are some basic ways to use the ngForward approach when migrating an existing Angular 1.x (must be 1.3+) apps to be more like a 2.0 app.

  1. Open the command line prompt and execute the following command. The command line prompt is opened at the existing Angular 1.x project root directory. When this command is executed, it will install the latest available version of ngForward including the reflect-metadata module.
npm i --save ng-forward@latest reflect-metadata
  1. Next, open the HTML file in the text editor and be prepared to make the following changes, as shown below:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Ng-Forward Migration EG</title>
    <link rel="stylesheet" href="styles.css" />
    <script data-require="angular.js@1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
    <script data-require="ui-router@0.2.15" data-semver="0.2.15" src="http://rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/systemjs/0.18.4/system.js"></script>
    <script src="config.js"></script>
    <script>
      //To bootstrap the Angular 2.0 application
      System.import('app').catch(console.log.bind(console));
    </script>
  </head>
  <body>
    <my-angular2-app>A moment please...</my-angular2-app>
  </body>
</html>
  1. We notice that the config.js file is declared in the head section of the index.html file above. This file is going to be created as shown below.
System.config({
  defaultJSExtensions: true,
  transpiler: 'typescript',
  typescriptOptions: {
    emitDecoratorMetadata: true
  },
  map: {
    'ng-forward': 'https://gist.githubusercontent.com/timkindberg/d93ab6e17fc07b4db7e9/raw/
b311a63e0e96078774e69f26d8e8805b7c8b0dd2/ng-forward.0.0.1-alpha.10.js',
    'typescript': 'https://raw.githubusercontent.com/Microsoft/TypeScript/master/lib/
typescript.js',
  },
  paths: {
    app: 'src'
  },
  packages: {
    app: {
      main: 'app-component.ts',
      defaultExtension: 'ts',
    }
  }
});
  1. Now in our app-component.ts file, we can code it in an Angular 2 way, as shown below.
import {Component,  bootstrap} from 'ng-forward';

@Component({
    selector: 'my-angular2-app',
    template: '<h3>{{heading}}</h3><p>{{paragraph}}</p>`
})
class AppComponent { 
    heading = "Welcome to Angular 2.0 framework";
    paragraph = "Hello World!";
}
bootstrap(AppComponent);

At this point, we are all set to use Angular 2 features in the existing Angular 1.3 app.

Using ngUpgrade approach

By using the ngForward approach, we can write the code in the Angular 2.0 way on top of the existing Angular 1.x applications. However, this approach may not be comfortable for some as concerns over its maintainability and backward compatibility with the future Angular versions could be an issue. The ngForward approach will definitely cause problems for bulky Angular 1.x applications in the long run. This problem has been nailed down to a large extent with the use of the ngUpgrade approach. The ngUpgrade approach has the comprehensive documentation which can be obtained from the official Angular website.

Conclusion

In this article, I have suggested a number of ways which could be taken into consideration in order to migrate existing applications from Angular 1.x to 2. Therefore, depending on the organizational need, the appropriate migration approach should be used.


Author’s Bio


Aparajita Jain is a senior Java developer and a technical writer with more than 6 years of experience. She has expertise in Java, PHP, and Python. She loves teaching and sharing knowledge. Currently working full time as Java developer in one of the leading banks in Canada.

Discover and read more posts from Codementor Team
get started
post commentsBe the first to share your opinion
APPNWEB Technologies LLP
7 years ago

HI
I am for the first time here. I found this board and I to find It really useful & it helped me out a lot.
I hope to provide one thing again and help others like
you helped me.
https://www.appnwebtechnologies.com

Takhir
7 years ago

Great article, than you, Aparajita! I would also add a bit of help for those who in general thinks about migrations from Angular 1.3/1.4 to 1.5 and wants to try Angular 2.0:

http://www.diatomenterprise…

Show more replies