How to migrate from Angular 1 to Angular 2?

With Angular 4 around the corner, now is a great time to migrate to Angular 2. There is no rush though as Angular 4 is just the next iteration of what is now called Angular, the new name for v2, 4, 5,6 and so forth. As a result, per the latest branding guidelines, this article should really be titled How to migrate from Angular JS to Angular?

1) Migrate to the latest version of Angular JS

As of right now, the latest version of Angular JS is 1.6. You should really consider upgrading because Angular JS 1.5+ has introduced features that are similar to what Angular now uses (components being the most important one). The main goal for 1.5 and 1.6 was to make the migration to Angular easier, so that’s the first step to take. The migration guide for all 1.x versions can be found here.

2) Get your 1.x code ready for Angular

First, remove $scope from your code and use the “controller as” syntax instead. Since Angular uses TypeScript classes, getting rid of $scope and using a syntax that is much closer to actual class properties makes perfect sense. Here is an example of a controller + HTML template that use the “controller As” syntax:

Then it would be a good idea to replace your controllers / directives with components, introduced in Angular 1.5. A component is a directive with a HTML template. Here is what a simple Angular 1.x component looks like – A directive with a HTML template:

The final step is to start learning and using TypeScript in your code. Since TypeScript transpiles down to ES5 code, you can already use TypeScript for development purposes and then deploy the resulting Javascript to production.

3) Upgrade incrementally to Angular

Angular has an upgrade adapter that allows you to mix and match Angulaar JS and Angular in the same app:

The next step is to use the upgrade adapter to migrate your code piece by piece. I would suggest to first upgrade your services, then directives / components. The reason for this is that services are not very different in Angular compared to what they were in Angular JS.

Finally, use the Angular component router and bootstrap your app with Angular.

4) Enjoy and relax!

Seems like an easy process? Not quite, right? That’s why I would only consider upgrading apps if a full rewrite is not an option. In most cases, it’s actually easier to build a new Angular project with CLI and create components / services inspired from your old Angular JS code.

It’s a great opportunity to only keep what you need and to learn Angular in the process as well.