Monday, June 27, 2016

Angular 2 Tutorial: Create a CRUD App with Angular CLI

Angular 2 is an open source framework for building mobile and desktop applications.

Rather than a successor of AngularJS 1.x, Angular 2 can be considered an entirely new framework built on learnings from AngularJS 1.x. Hence the name change where Angular is used to denote Angular 2 and AngularJS refers to AngularJS 1.x. In this article we will use Angular and Angular 2 interchangeably but they both refer to Angular 2.

In this article we'll be building an Angular 2 Todo web application that allows users to:

  • quickly create new todo's using an input field and hitting the enter key
  • toggle todo's as complete or incomplete
  • remove todo's that are no longer needed

Animated GIF of finished Angular 2 tutorial application

Here is a live demo of the application we will be building.

All code is publicly available right here so feel free to fork and play with the code yourself.

Let's get started!

The Angular CLI

One of the easiest ways start a new Angular 2 application is to use the brand new Angular command-line interface (CLI) that allows you to:

  • generate boilerplate code for new Angular 2 applications
  • add features (components, directives, services, pipes, etc) to existing Angular 2 applications

To install Angular CLI, run:

$ npm install -g angular-cli

which will install the ng command globally on your system.

To verify whether your installation completed successfully, you can run:

$  ng version

which should display the version you have installed.

You can visit the official installation notes for more information if needed.

Generating Our Todo Application

Now that we have Angular CLI installed, we can use it to generate our Todo application:

$ ng new angular2-todo-app

This will create a new directory for us with everything we need to get started:


├── angular-cli-build.js
├── angular-cli.json
├── config
│   ├── environment.dev.ts
│   ├── environment.js
│   ├── environment.prod.ts
│   ├── karma.conf.js
│   ├── karma-test-shim.js
│   └── protractor.conf.js
├── e2e
│   ├── app.e2e-spec.ts
│   ├── app.po.ts
│   ├── tsconfig.json
│   └── typings.d.ts
├── package.json
├── public
├── README.md
├── src
│   ├── app
│   │   ├── app.component.css
│   │   ├── app.component.html
│   │   ├── app.component.spec.ts
│   │   ├── app.component.ts
│   │   ├── environment.ts
│   │   ├── index.ts
│   │   └── shared
│   │       └── index.ts
│   ├── favicon.ico
│   ├── index.html
│   ├── main.ts
│   ├── system-config.ts
│   ├── tsconfig.json
│   └── typings.d.ts
├── tslint.json
├── typings
│   └── ...
└── typings.json

You can now:

# enter new directory the CLI created for you
$ cd angular2-todo-app

# start the development server
$ ng serve

which will start a local development server that you can navigate to in your browser on http://localhost:4200/.

The application will automatically reload when a source file has changed.

How convenient is that!

Angular Ingredients

Angular CLI already generated the entire Angular 2 application boilerplate for us when we used the ng new command. But it doesn't stop there. It can also help us add ingredients to our existing Angular application using the ng generate command:

# Generate a new component
$ ng generate component my-new-component

# Generate a new directive
$ ng generate directive my-new-directive

# Generate a new pipe
$ ng generate pipe my-new-pipe

# Generate a new service
$ ng generate service my-new-service

# Generate a new class
$ ng generate class my-new-class

# Generate a new interface
$ ng generate interface my-new-interface

# Generate a new enum
$ ng generate enum my-new-enum

If you are not familiar with the basic building blocks of an Angular 2 application, it is highly recommended that you read the Angular 2 QuickStart first.

To meet the needs of our Todo application, we will need:

  • a Todo class to represent individual todo's
  • a TodoService to create, update and remove todo's
  • a TodoApp component to display the user interface

So let's add these ingredients one by one.

Creating the Todo Class

Because we use TypeScript, we can use a class to represent Todo items, so let's use Angular CLI to generate a Todo class for us:

$ ng generate class Todo

which will create:

src/app/todo.spec.ts
src/app/todo.ts

Let's open up src/app/todo.ts and replace its contents with:

export class Todo {
  id: number;
  title: string = '';
  complete: boolean = false;

  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
}

Each Todo item has 3 properties:

  • id: number, unique ID of the todo item
  • title: string, title of the todo item
  • complete: boolean, whether or not the todo item is complete

The constructor logic allows us to specify property values during instantiation:

let todo = new Todo({
  title: 'Read SitePoint article',
  complete: false
});

In fact, Angular CLI generated src/app/todo.spec.ts for us so let's add a unit test to make sure the constructor logic works as expected:

import {
  beforeEach, beforeEachProviders,
  describe, xdescribe,
  expect, it, xit,
  async, inject
} from '@angular/core/testing';
import {Todo} from './todo';

describe('Todo', () => {

  it('should create an instance', () => {
    expect(new Todo()).toBeTruthy();
  });

  it('should accept values in the constructor', () => {
    let todo = new Todo({
      title: 'hello',
      complete: true
    });
    expect(todo.title).toEqual('hello');
    expect(todo.complete).toEqual(true);
  });

});

To verify whether our code works as expected, we can now run the unit tests:

Continue reading %Angular 2 Tutorial: Create a CRUD App with Angular CLI%


by Todd Motto via SitePoint

No comments:

Post a Comment