Tuesday, February 2, 2016

Getting Past Hello World in Angular 2

This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.

So you've been through the basic Angular 2 application and now you want a bit more. If you've been reading about Angular 2 you've undoubtedly seen what might look like really odd syntax in templates. You may have heard something about an overhaul to dependency injection. Or maybe some of the features of ES7 (or ES2016, the version of JavaScript planned to come out next year) such as Decorators and Observables.
[author_more]
This post will give you a quick introduction to these concepts and how they apply to your Angular 2 applications. We won't dive deep into these topics yet, but look for later posts that cover each area in more detail.

So, let's begin at the beginning–setting up an environment.

Environment Setup

Angular2 source is written in TypeScript, a superset of JavaScript that allows for type definitions to be applied to your JavaScript code (you can find more information about TypeScript at http://ift.tt/RuU3Y2).

In order to use TypeScript, we need to install the compiler which runs on top of Node.js. I'm using Node 0.12.6 and NPM 2.9.1. TypeScript should be installed automatically by NPM, but you can also install TypeScript globally using:


npm install –g typescript
# Test using
tsc -v

We are also using Gulp to build the project. If you don't have Gulp installed globally, use this command:

npm install -g gulp-cli

Once you have Node installed, use these instructions to set up and start your simple application:


git clone http://ift.tt/1QajOaW
cd second-angular-app
npm install
gulp go

In a browser, navigate to http://localhost:8080 (or the deployed version at http://ift.tt/1SDakJK). You should see an extremely basic application like this:

Basic Angular 2 application

This is a simple application that takes comma-separated ticker symbols as input and retrieves data including price and the stock name, displaying them in a simple list. This lacks styling, but we can use it to demonstrate a few ways to think about Angular 2 applications.

Components

Angular 2 applications are built using components. But what is a component? How do we set up a component in Angular 2?

At a high level, a component is a set of functionalities grouped together including a view, styles (if applicable) and a controller class that manages the functionality of the component. If you're familiar with Angular 1, a component is basically a directive with a template and a controller. In fact, in Angular 2 a component is just a special type of directive encapsulating a reusable UI building block (minimally a controller class and a view).

We will look at the pieces that make up a component by examining the StockSearch component. In our simple application, the StockSearch component displays the input box and includes a child component called StockList that renders the data returned from the API.

Decorators

Decorators are a new feature in ES7 and you will see them identified in source code by a leading "@" symbol. Decorators are used to provide Angular with metadata about a class (and sometimes methods or properties) to they can be wired into the Angular framework. Decorators always come before the class or property they are decorating, so you will see a codeblock like this:

Decorators

This block uses the component decorator to tell Angular that MyClass is an Angular component.

Note: For an in-depth discussion of decorators and annotations (a special type of decorator used in Angular 2) see Pascal Precht's post on the difference between annotations and decorators.

Examining a Component

Let's get into some code. Below is the StockSearch component, responsible for taking user input, calling a service to find stock data, and passing the data to the child StockList component. We will use this sample to talk about key parts of building an Angular 2 application:


import {Component, View} from 'angular2/core'
import {StockList} from './stockList'
import {StocksService} from '../services/stocks'

@Component({
        selector: 'StockSearch',
        providers: [StocksService]
})
@View({
template: `
        <section>
        <h3>Stock Price & Name Lookup:</h3>
        <form (submit)="doSearch()">
        <input [(ngModel)]="searchText"/>
        </form>
        <StockList [stocks]="stocks"></StockList>
        </section>
          `,
        directives: [StockList]
})
export class StockSearch {
        searchText: string;
        stocks: Object[];

        constructor(public stockService:StocksService) {}

        doSearch() {
                this.stockService.snapshot(this.searchText).subscribe(
                        (data) => {this.stocks= data},
                        (err) => {console.log('error!', err)}
            );
        }
}

(Screenshots in this post are from Visual Studio Code in Mac.)

While I’m relatively new to TypeScript, I’ve been enjoying it while writing Angular2 applications. TypeScript’s ability to present type information in your IDE or text editor is extremely helpful, especially when working with something new like Angular2.

I’ve been pleasantly surprised with how well Visual Studio Code integrates with TypeScript. In fact, it’s written in TypeScript and can parse it by default (no plugins required). When coding in Angular2 I found myself referring to the documentation frequently until I found the “Peek Definition” feature. This feature allows you to highlight any variable and use a keyboard shortcut (Opt-F12 on Mac) to look at the source of that variable. Since Angular2’s documentation exists in the source, I find I rarely need to go to the online documentation. Using Peek Definition on the Component decorator looks like this:

Peek Definition on the Component decorator

Continue reading %Getting Past Hello World in Angular 2%


by Jason Aden via SitePoint

No comments:

Post a Comment