Moving to Angular 2 – A Learning Story

This Article is written to explain my expreriences when i was moving to Angular 2. A few months ago, i was using Goole’s Angular for 2 projects. I learned Angular 1.x from Codeschool‘s classes. Also it was my first time, learning with interactive coding websites. Codeschool gave me really good experience about interactive learning. They explain everything in videos, downloadable presentations and then you can learn Angular, hands on approach.

Angular Story of Mine

I think i haven’t use Angular since July, it’s 8 months. But i followed news about Angular on Twitter. Today morning, i decided to use Angular 2 in a my side project. Beacuse it seems like it worths learning. The first tutorial i read is angular.io‘s tutorial. At first i was a little bit shocked. Because Angular 2 uses Typescript! I tought, “ooh it’s only one tutorial, thay may wanted to use Typescript, let’s check other tutorials to see some plain Javascript code”. There were no plain Javascript code, may moving to angular 2 was becoming a nightmare.  For next few hours i was like that “come on, what happened to Javascript. Why Google’s product based on a Microsoft product?” (I know Mircosoft supports Typescript to be an open standart)

Typescript? Why Google!?

Actually, i tried Typescript to learn it, but not on a project. It was only to trying to learn. This topic on Quora explains about Google’s decision on Typescript. I am big fan of Javascript since a year an half, because I am able to do everyth

ing i need using only a language. I can write backend services, frontend, mobile applications, games and desktop applications. One of my Angular projects was a desktop applications. I choosed Angular because it’s superfast and it makes me able to write organizable code. I realized that, i was thinking about purely object oriented Javascript might be cool to write destkop applications.  Then i realized, Google’s selection about Typescript is very good for angular, to get used in every kind of coding. Especially for large code based projects, Typescript will boost teams productivity.

To learn Typescript you can check out official demos of Typescript. It was not hard for a OOP backed programmer.

Getting Started With Angular 2

And where to start learning first? On Angular 1, everything starts with bootstrapping an Angular project. So bootstrapping an Angular 2 project will be first topic to learn when moving to angular 2.

Preparing for Angular 2

You should install Typescript to transpile your code into Javascript, it is super easy using NPM. Just run the command:

npm install -g typescript

But you don’t need Typescript installed on your systems to develop Angular apps.

Bootstrapping an Angular 2 Project

First you should include all Javascript files in your html file. Then you should declare transpiler and the main file of your Angular project. For example Angular.io’s  index.html examples is that:

<!DOCTYPE html>
<html>
  <head>
    <title>Angular 2 Hello World</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 1. Load libraries -->
    <!-- IE required polyfills (from CDN), in this exact order -->
    https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js
    https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.16/system-polyfills.js
    https://code.angularjs.org/tools/system.js
    https://code.angularjs.org/tools/typescript.js
    https://code.angularjs.org/2.0.0-beta.7/angular2-polyfills.js
    https://code.angularjs.org/2.0.0-beta.7/Rx.js
    https://code.angularjs.org/2.0.0-beta.7/angular2.dev.js
    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}}
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <hello-world>Loading...</hello-world>
  </body>
</html>

As you can see, System.config() function declares all main settings about your application. This script registers, app/main.ts script.

import {bootstrap}  from 'angular2/platform/browser';
import {HelloWorld} from './hello_world';

bootstrap(HelloWorld);

I won’t copy all code here. You can found codes at angular.io, but i only wanted to say that, Angular 2 project bootstrapping is far better than Angular 1 project definition.

At this point i wanted to learn how to make rest api calls using Angularjs. My api has been ready for a while to register a user. I created a new project and concentrated on making api calls using Angular 2.

To get started, i should be able to design a form, submit it and read values. ngModel was really good tool for doing that but it seems like a little bit changed since Angular 1.X. Angular has been dropped Controllers, so we need a component based approach to design out form logic.

I figured out how to parse a form in Angular 2, but it was not the usual way for Angular. They designed a new FormBuilder class to make a good form design, i won’t put here all codes about parsing bu i just want to show you FormBuilder example. (I Also tried, Visual Studio Code, it was very usable for Typescript apps.)

Here is registerpage.ts

import {Component} from 'angular2/core';
import {FormBuilder, Validators, Control} from 'angular2/common';
import {bootstrap} from 'angular2/platform/browser';

@Component({
    selector: 'register-form',
    templateUrl: 'http://localhost:8080/app/registerpage.html'
})

export class RegisterPage {
  userForm: any;
  
  constructor(private _formBuilder: FormBuilder) {  
    this.userForm = this._formBuilder.group({
        'password': ['', Validators.required],
        'name': ['', Validators.required],
        'email': ['', Validators.required]
    });
  }
  
  saveUser() {
      console.log("button clicked");
      alert(`Name: ${this.userForm.value.name} Email: ${this.userForm.value.email}`);
  }
}

Here is registerpage.html

<h1>form</h1>
<form [ngFormModel]="userForm" (submit)="saveUser()">
    <input ngControl="email" id="email" type="email" #email="ngForm" placeholder="Your email">
    <input ngControl="password" id="password" type="password" #password="ngForm" placeholder="Your Password">
    <input ngControl="name" id="name" type="name" #name="ngForm" placeholder="Your Name">
  <button type="submit">Register</button>
</form>

I am able to read data through forms, so i need to add http post request mechanism for communicating with server.

After trying really hard for an hour, i found the way to make a http request to the server. You should enable cors on your server first, i am using node js with express framework, it is really easy to enable it, but don’t forget about enabling your server “options” method to send cors headers too.

My registerpage.ts script became that (i know it looks like hell but, you know, i am only trying to achieve something)

import {Component} from 'angular2/core';
import {Http, HTTP_PROVIDERS, Headers} from 'angular2/http';
import {FormBuilder, Validators, Control} from 'angular2/common';
import {bootstrap} from 'angular2/platform/browser';
import 'rxjs/add/operator/map';

@Component({
    selector: 'register-form',
    templateUrl: 'http://localhost:8080/app/registerpage.html'
})

export class RegisterPage {
  userForm: any;
  requestObject: any;
  http: any;
  
  constructor(private _formBuilder: FormBuilder, http: Http) {  
    this.userForm = this._formBuilder.group({
        'password': ['', Validators.required],
        'name': ['', Validators.required],
        'email': ['', Validators.required]
    });
    
    this.http = http;
  }
  
  saveUser(e) {
      e.preventDefault();
      console.log("button clicked");
      this.requestObject = {
          name: this.userForm.value.name,
          password: this.userForm.value.password,
          mail: this.userForm.value.email
      };
      var stringRequestObject = JSON.stringify(this.requestObject);
      console.log(stringRequestObject);
      
      var headers = new Headers();
      headers.append('Content-Type', 'application/json');
      this.http.post('http://localhost:3000/user/register', stringRequestObject, {
          headers: headers
      }).map(res => res.text())
        .subscribe(
            data => console.log(data),
            err => console.log(err),
            () => console.log('Random Quote Complete')
        );
  }
}

I uploaded all code to github, you can check by clicking here.

My adventure with angular 2 is started with this article. Moving to angular 2 seems like a going to be painful for me.

I am a little bit tired after all that thing, i’ll try to write ASAP again about Angular 2.

Leave a Reply

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