Day-1 :Getting started with Angular 2

Goal : Create an Angularjs 2 (AJ2) application to access REST API and has nested components with event handling

Mansura H.
Web Application Development
5 min readSep 14, 2016

--

Pre-Requirement: NodeJs

Creating the Starter AJ2 seed application

I pat on my back for not being lazy and download one of the existing angular-2 starter kit from github, as there are a number of them. Instead I have followed the instructions given official angular website. This helps me to understand the functionalities and structure of different files and dependencies used in application. So finally, I have my AJ2 seed application.

The alternative way could be as following,

  • download any starter AJ2 app. (e.g AJ2 seed application)
  • run “npm install -g webpack webpack-dev-server typings typescript” from command line from the root directory of the downloaded project
  • run “npm install” from command line from the root directory of the downloaded project
  • run “npm start” to fire up dev server
  • open browser to http://localhost:8080

The alternative way with angular-cli could be as following,

  • Install angular-cli using following comamnd
npm install -g angular-cli
  • create a new folder and from the command prompt run the following command, here ‘helloworld’ is the project name. This command will create a project with all necessary files and configuration.
ng new helloworld
  • to run the project run the folllowing comamnd
ng serve
  • open browser to http://localhost:4200

Creating Card Component

Step 1.1 — Create files

In folder src/app, create a new folder called ‘card’. All related components to this component will be inside this folder.

  • card.component.ts
  • card.component.css
  • card.component.html
//src/app/card/card.component.tsimport { Component, OnInit, Input } from '@angular/core';@Component({
selector: 'my-friend',
templateUrl: './card.component.html',
styleUrls: ['./card.component.css']
})
export class CardComponent implements OnInit{
@Input() friend;
ngOnInit() { }
}

Every card component has an input field called ‘friend’. Each friend will have data regarding name, email etc. Therefore, our card will look as folllwoing

A Card Component with a friend Object.

Step — 1.2: Import Card component in app.module.ts

//src/app/app.module.ts
import { CardComponent } from './card/card.component';
@NgModule({
... ... ... ... ... ...
declarations: [ AppComponent , CardComponent]
... ... ... ... ... ...
})

Step — 1.3: Event Handler

There are two events need to be handled for this Card Component.

  1. On initialization of the component, the first list item would be active and the information section will have corresponding information related to the first item.
  2. In this card component, inside the event handling section, there are six list item and on mouse-hover of each list item, the information section is updates with relevant information.

For solving the first case, ngOnInit() is enough. selectPerson(‘name’) will call selectPerson method change selectedValue and title variable based on the passed parameter ‘name’.

In order to solve the second case, we need to use mouseover. Instead of ng-mouseover=”method()” in angularjs 1, in AJ2 the syntax would be as following:

//src/app/card/card.component.html
... ... ... ... ... ...
<ul class="values_list horizontal_center" id="values_list" >
<li data-label="name" [class.active]="na"
(mouseover)="selectPerson('name')"
(mouseout)="na=false"></li>
... ... ... ... ... ...
</ul>
... ... ... ... ... ...

It will call the method ‘selectPerson’ in card component.

//src/app/card/card.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'my-friend',
templateUrl: './card.component.html',
styleUrls: ['./card.component.css']
})
export class CardComponent implements OnInit{
selectedValue: string;
title: string;
componentName: string = 'CardComponent';
@Input() friend;
na:boolean;
em:boolean;
loc:boolean;
pass:boolean;
mouseover:boolean;
bday:boolean;
ngOnInit() { this.selectPerson('name'); }

selectPerson(label){
console.log("here"+label);
if(label === 'name') {
this.selectedValue = this.friend.name.title + " "+ this.friend.name.first+" "+this.friend.name.last;
this.na= true;
this.title= "Hi, My name is";
}
else if(label === 'email') {
this.selectedValue = this.friend.email;
this.em= true;
this.title= "My email address is";
}
else if(label === 'location') {
this.selectedValue = this.friend.location.street + " "+ this.friend.location.city+" "+this.friend.location.state;
this.loc= true;
this.title= "My address is";
}
else if(label === 'pass') {
this.selectedValue = this.friend.login.password;
this.pass= true;
this.title= "My password is";
}
else if(label === 'phone') {
this.selectedValue = this.friend.phone;
this.mouseover= true;
this.title= "My phone number is";
}
else if(label === 'birthday') {
this.selectedValue = this.friend.dob;
this.bday= true;
this.title= "My birthday is";
}
}
}

Creating Service to access REST endpoint

The main goal is to access REST endpoint to get a list of person/friend and display those persons in card component inside cardlist component. Therefore, in order to access REST endpoint we need a service.

Step — 2.1 : Create a file called src/app/card/card.service.ts

Service needs to be injectable and as we are accessing Webservice, we also need Http, Response model. As we are making Async request and change in real time, we need to use Observable. we can also use promise. However, I love observable.

//src/app/card/card.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class CardService {
constructor (private http: Http) {}
private url = 'http://api.randomuser.me/?results=10';
getCards () {
return this.http.get(this.url)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return res.json();
}
private handleError (error: any) {
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
return Observable.throw(errMsg);
}
}

Step — 2.2 : Update app.module.js

As we have used Http, we need a provider for that. so in app.module.ts add the following lines:

//src/app/app.module.tsimport {HttpModule} from "@angular/http";
@NgModule({
imports: [ BrowserModule , HttpModule],
...
})

Creating Wrapper component

Step — 3.1: create CardList Component in card folder

  • As CardService and CardComponent are used in this component, they have been impoted.
  • Inside the Component definition CardService has been added as providers
  • It has an observable variable which is a list of object returned as response of the API call.
  • ‘results’ is the json field in thre response object containing the array of Person object, therefore, res =>this.friends = res.results
  • In order to use CardService in a method, we need to initialize the service in the constructor.
  • Then, inside ngOnInit(), the method has been called
  • The Observable has been subscribed here in method getCards(). In subscribing there are three distinctive callbacks: the first receive the response as new value for @Input friends, the second one is for any errors and the last one is used to represent the function to be invoked when the sequence of incoming data is complete and the Https request is successful.
//src/app/card/cardlist.component.tsimport {Component,OnInit, Input, Output} from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import { CardService } from './card.service';
import { CardComponent } from './card.component';
@Component({
selector: 'my-friends',
templateUrl: './cardlist.component.html',
providers: [CardService]
})
export class CardListComponent implements OnInit {
errorMessage: string;
@Input() friends;
constructor (private _cardService: CardService) {}ngOnInit() { this.getCards(); }getCards() {
this._cardService.getCards()
.subscribe(
res => this.friends = res.results,
error => this.errorMessage = error),
() => this.finished = true;
}
}

Step — 3.2 : change app.component.html

As the selector in CardListComponent is my-friends, we need to change template of parent component, which is AppComponent.

So <my-friends></my-friends> will hold CardListComponent.

//src/app/app.component.html<main>
<h1>Hello from Angular 2 App with Webpack</h1>
<!-- <img src="../../public/images/coffee.jpg">-->
<my-friends></my-friends>
</main>

Step — 3.3: Import CardListComponent in app.module.ts

//src/app/app.module.ts
import { CardListComponent } from './card/cardlist.component';
@NgModule({
... ... ... ... ... ...
declarations: [ AppComponent , CardComponent, CardListComponent]
... ... ... ... ... ...
})

Finally, the results is here as following:

Event + REST + Component+ Nested Component+ Observable

GitHub!

--

--

Mansura H.
Web Application Development

Platform Architect @ IBM; Author of Hybrid Cloud Infrastructure and Operations Explained ..