Angular 1 to Angular 2 Journey

In this post, we will see how to convert Angular 1 knowledge into Angular 2.

Assumptions:
We can write Angular 1 in both JavaScript ES5 and ES6.
Angular 2 in TypeScript and JavaScript.

We will use JavaScript ES5 for Angular 1 and TypeScript for Angular 2 in this post.

1) Modules

For both Angular 1 and Angular, 2 Modules are a great way to organzine application code. We can group different controller (or) Component and providers via modules.

Angular 1

angular  
  .module('AppModule', [])

This will create a module.

Angular 2

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

@NgModule({
  imports: [ ],
  declarations: [ ],
  bootstrap:    [ ]
})
export class AppModule { }  

We use @NgModule decorator to create module in Angular 2.

2) Components

Angular components are the way to group template and javascript functionality code together.

From Angular 1.5 onwards we have .component API in angular 1. Let's use it here. we can also create components using directives but we will use .component here.

Angular 1

var app = angular.module('app'); // module getter  
app.component('AppComponent', {  
  bindings: {
    uname: '<'
  },
  template: '<h1>Hellow welcome {{uname}}</h1>',
  controller: function() {
      // any logic here
  }
});

.component expected a object with bindings, 'template' and 'controller()' properties. Of course, there are few more but we will use only this here.

in your HTML, you can write.

In Angular 1 the component name AppComponent converted to dashed case and use as HTML tag.

bindings objects contains input and output parameter of that component. Here < represents input binding.

template hold HTML template of that component.

controller() contains all functionality code for that component.

 <app-component uname="John"></app-component>

Angular 2

import { @Component, @Input } from '@angular/component';

@Component({
  selector: 'app-component',
  template: `<h1>This is App Component</h1>`,
})
export class AppComponent {  
   @Input() uname: string;
}

We need to tell angular where to look for this component.

import { HttpModule }    from '@angular/http';  
import { NgModule }      from '@angular/core';  
import { AppComponent } from '../app.component'

@NgModule({
  imports: [
    HttpModule
  ],
  declarations: [
   AppComponent
  ],
  providers: [ ],
  bootstrap: [ ]
})
export class AppModule { }

If it's a component or Directive we need to add it to the declarations array of @NgModule metadata.

now in our HTML

<app-component [uname]="John"></app-component>  

Angular 2 uses @Component decorator on class AppComponent which expects a metadata object.

selector is for HTML tag what we want to create.

template holds HTML template which is same as.

class AppComponent instead of controller() in Angular 1 here we have a class to hold the functionality of the component.

Here we have @Input decorator which is used for getting inputs for the component. Simpler to the bindings in angular but in Angular 1 bindings can have both input, output, and two-way bidding. In Angular 2 we have only @Input, @Output bindings.

2) Directives

Angular 1 directives are same as Components . In fact, Angular 1 component internally use directive API to create a component. Basically, directives are the way to create new HTML tags.

var app = angular.module('App', []);

app.directive('myAvatar', function() {  
  return {
    template: '<h1>This is custom html tag</h1>'
  };
});

this code will create an HTML tag.

<my-avatar></my-avatar>  

which html page loaded we will see

<h1>This is custom html tag</h1>  

on the page.

In Angular 2 we have three kinds of Directives

  1. Components directives with a template.
  2. Structural directives—change the DOM layout by adding and removing DOM elements.
  3. Attribute directives—change the appearance or behavior of an element.

    Components are something we already saw before. Structural and Attribute directives can be used to manipulate the DOM of an element.

In Angular 2 we see structural directives like *ngIf, *ngFor. Creating custom structural directives are out of the scope of this post. I will write an another blog post about it.

Now let's create a simple Attribute directive.

import { Directive, ElementRef,  
         Input, Renderer } from '@angular/core';

@Directive({ 
  selector: '[makeMeYellow]' 
})
export class MakeMeYellowDirective {  
    constructor(el: ElementRef, renderer: Renderer) {
       renderer.setElementStyle(el.nativeElement, 'color', 'yellow');
    }
}

Again need to tell angular where to look for this Directive. We can do this by adding this directive to the @NgModule.

import { HttpModule }    from '@angular/http';  
import { NgModule }      from '@angular/core';  
import { MakeMeYellowDirective } from '../make-me-yellow.direcive'

@NgModule({
  imports: [
    HttpModule
  ],
  declarations: [
   MakeMeYellowDirective
  ],
  providers: [ ],
  bootstrap: [ ]
})
export class AppModule { }  

What this directive does is it will change the text color of the HTML node it is applied to.

All valid CSS selector can be used with Selector properties in entire Angular 2.

to use this.

<p makeMeYellow class="main-text"> lorem ipsam </p>  

3) Services

Angular 1 we have three kinds of services providers,services and factories.
In Angular 2 we have only one service which is almost equivalent to angular 1 .service API.
let's see an example with it.

var app = angular.module('App', []);  
app.service('GitHubService', [$http,function($http){  
   var apiUrl = 'http://api.github.com/users';
   var self = this;
   this.data = [];

   this.getUsers = function() {
       return $http.get(apiUrl).then(function(userData) {
         self.data = userData;
      }); 
   }
}]);

In Angular 2 we have only one way to create service.

import { Injectable } from '@angular/core';  
import { Http } from '@angular/http';

@Injectable()
export class GitHubService {  
   private apiUrl:string = `http://api.github.com/users`;
   private data:Array<any>;

   // inject Http service into this service
   constructor(private http: Http) {

   }
   // get Github users
   getUsers() {
        return this.http.get(this.apiUrl).toPromise();   
   }
}

Angular 1 and Angular 2 have almost similer implmention for services. Please not Angualr 2 doesn't have http module by default we need to import the HttpModule when we bootstrap our appliction.

import { HttpModule }    from '@angular/http';  
import { NgModule }      from '@angular/core';  
import { GitHubService } from '../git-hub-service'

@NgModule({
  imports: [
    HttpModule
  ],
  declarations: [

  ],
  providers: [ GitHubService ],
  bootstrap: [ ]
})
export class AppModule { }  

Here we did two things. We imported HttpModule and added it to our AppModule via imports array and imported GitHubService which created earler and added it to our AppModule via providers property of the @NgModule;

4) Controller

Just to refresh our memory in Angular 1 we can write our controllers

var app = angular.module('App',[]);

app.controller('MainCtrl', function(){  
    // function inside a controller
    this.onSignupClick = function(){
        console.log('Signup button clicked');
    }
});

We can apply this controller as

<div ng-controller="MainCtrl as vm">  
     <button ng-click="vm.onSignupClick()"></button>
</div>  

But in Angular 2 we don't have any concept such as creating separate controllers. Instead, everything in Angular 2 is Components So no controller concept in Angular 2.

5) Filters

Filter have many usages in Angular. Basically, we use Filters format and filter the data in UI side.

Let's create simple Filter in Angular 1

var app = angualr.module('App',[]);

app.filter('uppercase', function(value){  
        return value.toUpperCase();
});

Now, To apply this filter

<p> Hellow my name is {{ name | uppercase}}<p>  

In Angular 2 Filters called as Pipes.

Let's implement the above filter in Angular 2.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'uppercase'
})
export class UppercasePipe implements PipeTransform {  
   transform(value: string): string {
      return value.toUpperCase();
  }
}

That's it. We have created a filter in Angular 2. In Angular 2 we use @Pipe decorator to implement the filter.
Inside the UppercasePipe class we should have a transform function to implemented.

Get posts by email

Like what you're reading? Get these posts delivered to your inbox.