Jake Partusch

Introduction

With Angular 2.0 right around the corner, big changes are in store. If you would like to understand the differences between Angular 1 and Angular 2 check out this blog post! For the past few years, building a Todo Application has been used as the “Hello World” of understanding a new framework, with just enough meat to get you going. If you already understand Angular 2.0 and just want a working example, visit the finished application here.

Disclaimer: Angular 2.0 is currently in Beta and the syntax is subject to change.

In this tutorial you will:

  • Explore the base of an Angular 2.0 application
  • Create and Angular 2.0 component
  • Add a new route
  • Implement Todo add/remove logic

Step 1: The Base

Angular 2.0 is written in TypeScript, a superset of the ES6 javascript standards. Although TypeScript is not required to build an Angular 2.0 application, the following examples will be written exclusively in TypeScript.

In order to get started the right foot, this tutorial with begin with a blank Angular 2.0 template. This includes a gulp build and the configurations you need to transpile the TypeScript. Since the usage of these common build tools are out of the scope of the this blog post, you might want to read up on Gulp, TSD, and Karma.

To get started, run the following commands:

git clone https://github.com/objectpartners/angular2-todo.git
cd angular2-todo
git checkout blank-template
npm install
npm run serve.dev

Step 2: Creating a new Component

First let’s create a new directory called ’todo' under ’app/components.' In the ’todo' directory add two new files called ’todo.component.ts' and ’todo.html,’ respectively. Combined, these two files will make up our component.

todo.component.ts

import { Component, CORE_DIRECTIVES } from 'angular2/core';

@Component({
  selector: 'todo',
  templateUrl: './components/todo/todo.html',
  directives: [CORE_DIRECTIVES],
})
export class TodoComponent {
  public todos: string[];
  constructor() {
    this.todos = [];
  }

  add(newtodo: string): boolean {
    //Our code will go here
  }

  remove(name: string): void {
    //Our code will go here
  }
}

Explanation of todo.component.ts

The ’@Component' annotation defines three properties: ’selector', ’templateUrl', and ’directives.’ The ’selector' property is the name that the component will bind to. In this case, whenever the ’<todo>' tag is used, this component will be injected. As you might have guessed, the ’templateUrl' defines the html template that will be injected in place of the selector tag. Finally, the ’directives' property defines any external directives that are used in the template. In this case, we import and use ’CORE_DIRECTIVES.’ This includes the basic directives built into Angular 2.0. The second part of this file defines the TypeScript class that will bind to the html file. In this case, we define two placeholder methods which we will fill in later.

todo.html

<div class="jumbotron">
  <div class="container">
    <div class="col-md-6 col-md-offset-3">
        <h1 class="text-center">Todos!</h1>
      </div>
    </div>
</div>
<div class="row">
  <div class="col-lg-6 col-lg-offset-3">
    <form (submit)="add(newtodo.value)">
        <div class="input-group">
          <input #newtodo type="text" class="form-control" placeholder="Add Todo...">
          <span class="input-group-btn">
            <button class="btn btn-default" type="submit">Add</button>
          </span>
        </div>
      </form>
    </div>
 </div>
 <br/>
 <div class="row">
  <div class="col-lg-6 col-lg-offset-3">
    <div class="panel panel-default">
        <div class="panel-heading">My Todos</div>
      <ul class="list-group">
        <li class="list-group-item" *ng-for="#todoitem of todos">
          <div class="row">
            <div class="col-xs-10">
              {{todoitem}}
            </div>
            <div class="col-xs-2">
              <button id="todo-remove" (click)="remove(todoitem)" type="button" class="btn btn-danger">Remove</button>
            </div>
         </div>
        </li>
      </ul>
    </div>
  </div>
 </div>

Explanation of todo.html

This HTML file, although mostly bootstrap style has a few key Angular 2.0 elements:_<form (submit)=“add(newtodo.value)“>_When the form is submitted, the add function will be called with the value of the local variable ’newtodo.’ This local variable is bound to the input text box._ng-for=“#todoitem of todos”>`Using the core directive, '\ng-for’we can iterate through the list of todos and assign each to an element 'todoitem.' This is very similar to an 'ng-repeat’in Angular 1.x.<button id="todo-remove" (click)="remove(todoitem)"_On the click of the button, the ‘remove’ function is called with the selected 'todoitem’` in the list

Step 3: Adding a Route

Let’s add a new route for our Todo Page. In Angular 2.0, routes are added using the ’@RouteConfig' annotation. Locate ’app.ts' in the project, and add:_{ path: ‘/todo’, component: TodoComponent, as: Todo }_Since we are using a new component in ’app.ts' we also need to be sure to import the component:_import {TodoComponent} from ‘../todo/todo.component’;_When you are completed, ’app.ts' should look like this:

import { Component, ViewEncapsulation } from 'angular2/angular2';
import { RouteConfig, ROUTER_DIRECTIVES } from 'angular2/router';

import { HomeComponent } from '../home/home.component';
import { TodoComponent } from '../todo/todo.component';

@Component({
  selector: 'app',
  templateUrl: './components/app/app.html',
  encapsulation: ViewEncapsulation.None,
  directives: [ROUTER_DIRECTIVES],
})
@RouteConfig([
  { path: '/', component: HomeComponent, as: 'Home' },
  { path: '/todo', component: TodoComponent, as: 'Todo' },
])
export class AppCmp {}

Then, add the link to the navbar. After editing, ’app.html' should look like this:

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="https://objectpartners.com/">
      	<img alt="Object Partners" src="/assets/ObjectPartnersLogo.png">
      </a>
    </div>
    <div >
      <ul class="nav navbar-nav">
        <li><a [router-link]="['/Home']">Home <span class="sr-only">(current)</span></a></li>
        <li><a [router-link]="['/Todo']">Todo</a></li>
      </ul>
    </div>
  </div>
</nav>

<section>
  <router-outlet></router-outlet>
</section>

Step 4: Adding the Todo Logic

Add these functions to ’todo.component.ts'

add(newtodo : string) : boolean {
   this.todos.push(newtodo);
   return false;
}
remove(name: string) : void {
  var index = this.todos.indexOf(name, 0);
  if (index !== undefined) {
     this.todos.splice(index, 1);
  }
}

Explanation

The add function is fairly straightforward, as we push the input string onto the array. We return false from this function so that we can also use the ‘Enter’ key to submit a todo. The remove function finds the first occurrence of to string and removes it from the array.

Wrap up

Congratulations on making your first Angular 2.0 Todo Application! You now understand the basic concepts of building TypeScript, creating a component, and setting up a route. If you run into any issues, please leave a comment, or submit an issue on GitHub.

Share this Post

Related Blog Posts

JavaScript

We want you to be MEAN !

January 14th, 2016

This blog assumes you are new to MEAN, and would like to install the components, and build your first MEAN application.

Larry Schoenfeld
JavaScript

Comparing React.js performance vs. native DOM

November 19th, 2015

React.js is a promising new library for Javascript view component development. I will be comparing performance of Reacts virtual DOM rendering approach against native DOM manipulation in Javascript.

Object Partners
JavaScript

Relational data management with Lovefield

October 8th, 2015

Relational data management with Lovefield

Mike Plummer

About the author

Jake Partusch

Sr. Consultant

Jake is a passionate web developer, a relentless tester, and a hobby hardware hacker. Jake has been a full-stack developer for over 4 years and has developed applications using Java, Spring, and AngularJS.