Instructions for Angular 2: Create CRUD App with Angular CLI

This is the first article in a four-part series of four tutorials on how to write a Todo application (task manager) in Angular 2:

  1. Part 1 – Install and launch the first Todo app version
  2. Part 2 – Create different components to display lists in todo and todo separately
  3. Part 3— Update serviceTodo to communicate REST API
  4. Part 4 – Use the Component Router to define different components

Note: Todo application is a simple application that reminds a series of tasks to be done on the day / week, with each todo is a job to be completed.

In this article, we will dive into the basic structure of the application to produce an application that looks like this:

By the end of this series, our application structure will look like this:

The items covered in red will be mentioned in this article, the remaining concepts will be introduced in the following articles of the series.

In this first part, you are taught how to:

  • Create Todo application with Angular CLI
  • Create the Todo class to represent separate todo items
  • Create the TodoDataService service to create, update and remove todo entries
  • Use the AppComponent element to display the user interface
  • Application Deploy to your GitHub page

Let's start!

Create Todo application with Angular CLI

One of the best ways to start an Angular 2 application is to use Angular's command-line interface (CLI).

To install the Angular CLI, run:

The above paragraph will install the ng gobal command on the system.

To confirm if the installation was successful, you can run:

The above code will display the version you have installed:

Once you've installed the Angular CLI, you can use the tool to create your Todo application:

This script will create a new folder with all the files needed to get started:

├── angular-cli.json
├── e2e
│ ├── app.e2e-spec.ts
│ ├── app.po.ts
│ └── tsconfig.json
├── karma.conf.js
├── package.json
├── protractor.conf.js
├── src
│ ├── app
│ │ ├── app.component.css
│ │ ├── app.component.html
│ │ ├── app.component.spec.ts
│ │ ├── app.component.ts
│ │ ├── app.module.ts
│ │ └── index.ts
│ ├── assets
Environments ├── environments
│ │ ├──
│ │ └── environment.ts
│ ├── favicon.ico
│ ├── index.html
│ ├── main.ts
│ ├── polyfills.ts
│ ├── styles.css
│ ├── test.ts
│ ├── tsconfig.json
│ └── typings.d.ts
└── tslint.json

If you're still not familiar with the Angular CLI, you can read more at The Ultimate Angular CLI Reference .

Now you can navigate to the new folder:

And start Angular CLI development server:

The command will start the local development server accessible from the http: // localhost: 4200 / browser.

The Angular CLI development server supports LiveReload, so every time the source file changes the browser will automatically reload the application.

Too convenient, guys?

Create Todo Class

Because the Angular CLI creates a TypeScript file, we can use the class to represent the todo entry:

Let's try using the Angular CLI to create a Todo class:

The command will create:

Please open src / app / todo.ts:

And more logic we need:

In this Todo class definition, we will specify that each Todo instance has 3 properties:

  • id: number, specific ID of todo item
  • title: string, name of todo item
  • complete: boolean, to do the finished item or not

We also have to provide the constructor logic that allows us to specify the property value during instantiation so that we can easily create new Todo instances as follows:

Come here, add unit tests to make sure our logic constructor works as expected.

When creating the Todo class, we used the -spec option. This option will cause the Angular CLI to also create src / app / todo.spec.ts with the basic unit test for us:

Add unit test to make sure the logic constructor works as expected:

To determine if our code is correct or not, we will now run:

to execute Karma test runner and run all unit tests we need. Your out will look like this:

After we have the Todo class working to represent a separate todo, then create the TodoDataService service to manage all todo entries.

Create TodoDataService Service

TodoDataService will take over the task of managing Todo items.

In the next parts of the series, we will learn the communication with EST API, but for now we will only store all data in memory.

Use the Angular CLI again to create the service:

With output:

When creating a service, the Angular CLI also creates unit tests by default, so there's no need to use the -spec option.

The Angular CLI created the following code for our TodoDataService in src / app / todo-data.service.ts:

And a corresponding unit test in src / app / todo-data.service.spec.ts:

Open src / app / todo-data.service.ts and add our todo management logic to TodoDataService:

The actual details of implementing the method are not necessary considering the purpose of this article. The key lesson is, we have to put the business logic at the center of the service.

To ensure the business logic in the TodoDataService service works as expected, we must also add some unit tests in src / app / todo.service.spec.ts:

Let's dive deeper into some of the unit tests above:

First of all, what is TestBed?

TestBed is a utility provided by @ angular / core / testing to tweak and create the Angular testing module so that we can run unit tests in it.

We use the TestBed.configureTestingModule () method to configure and create new Angular testing modules. We can configure testing the module as we like by passing in a configuration object. This configuration object has most of the properties of an ordinary Angular module .

In this case we can use the provider properties to fine tune the testing module to use TodoDataService when running the test.

Next, we will use the inject function by @ angular / core / testing to inject the correct service from the TestBed injector into our test function:

The first argument of the inject function is an array of Angular dependency injection tokens. The second argument is that the test function has parameters that are dependencies corresponding to dependency injection token from the array.

Here we require TestBed injector to inject TodoDataService by specifying in array in the first argument. Thus, we can take advantage of TodoDataService as a service in the test function because service is the name of the first parameter in our test function.

To determine if our service works as expected, run unit test again:

Perfect, all unit tests have run successfully!

Now that serviceTodoDataService is running well, it's time to build the user interface.

In Angular 2, the sections in components are shown.

Edit the AppComponent component

When we create the Todo application, Angular CLI automatically creates the main AppComponent component for us:

Please open src / app / app.component.html:

And replace its content with:

Below is a brief introduction to sample syntax in Angular if you still haven't seen:

  • [property]="expression" : set the properties of an element to the expression value (value of expression)
  • (event)="statement" : executes the command when the event occurs
  • [(property)]="expression" : create two-way binding with expression
  • [class.special]="expression" : add a special CSS class to the element when the expression value is true (truthy)
  • [style.color] =" expression ": set the color CSS property to the expression value

Let's see what these syntaxes will do with our interface. At the top, there will be an input box to create new todo:

  • [(ngModel)]="newTodo.title" : add two-way binding between input value and newTodo.title
  • (keyup.enter)="addTodo()" : the request Angular executes addTodo () press enter while typing input element.

(You might be wondering where the newTodo with addTodo () comes from, we'll talk about this soon.)

Next, we will go to the existing todo section:

* ngIf =" todos.length> 0 ″ : displays only the section element element and child elements at points with at least one todo.

In that section, we asked Angular to create a li element for each todo:

  • * ngFor =" let todo of todos ": loop all todo and assign the current todo to a variable with the name todo with each iteration
  • [class.completed] =" todo.complete ": apply complete class CSS to the li element when todo.complete is correct (truthy)

and finally, we will understand the details of what to do for each todo:

  • (click) =" toggleTodoComplete (todo) ": execute toggleTodoComplete (todo) and checkbox is clicked
  • [checked] =" todo.complete ": specify the value of todo.complete to the checked property of the element
  • (click) =" removeTodo (todo) ": execute removeTodo (todo) when clicking on the destroy button

OK, take a breath. We have been studying the syntax for a while now.

Many people wonder why those like addTodo () and newTodo.title can be evaluated. And the component instance is the instance of the component class.

Component class for AppComponent is defined in src / app / app.component.ts.

The Angular CLI created before a little boilerplate code.

So we can immediately start adding custom logic.

We will need the TodoDataService service in the AppComponent logic, so start by injecting the service into the componet.

First we will import TodoDataService and define the providers array of decorator Component.

Dependency injector AppComponent now takes the TodoDataService class to do dependency injection token and returns the only instance of TodoDataService.

Now that the dependency injector knows what to do, we will ask it to inject the TodoDataService instance of the component into the component by specifying the dependency in the AppComponent constructor:

Using public or private on the argument in the constructor is a shorthand notation that allows us to automatically create properties with this name, so:

stands for:

We can now implement all logical views by adding properties and methods to the AppComponent class:

We will first define a newTodo property and assign new Todo () when the component class is instantiated. This is the same Todo instance defined in the expression of [[(ngModel)]:

As soon as the input value changes in the view, the value in the component instance is updated. And every time the value in the component instance changes, the value in the input element in the view will be updated.

Next, we will implement all the methods we used in view:

The implementation process is very short, and it must be easy to understand when delegating all business logic to todoDataService.

(The business logic mandate for a service service is a very useful programming habit because we can manage and test.)

Before previewing the results on the browser, run unit test again:

The three tests failed because of the following error: an't bind to 'ngModel' since it is not a known property of 'input'..

Open src / app / app.component.spec.ts up:

The reason Angular complains is that it does not know ngModel is because FormsModule is not loaded when AppComponent is instantiated by Karma with the TestBed.createComponent () method.

(To learn more about TestBed, you should read the Official Angular documentation on testing .)

To ensure Angular also loads FormsModule when Karma instantiates AppComponent with TestBed.createComponent () , we must specify FormsModule in the imports property of the Testbed configuration object:

We now have 2 failed tests:

Karma warns us that the component instance does not have the title property equal to app works! And that no h1 element contains app works!.

That's true because we changed the logic component and template. So update unit tests accordingly:

Chúng ta trước hết sẽ thêm unit test để đảm bảo tính chất newTodo được thực thể hóa đúng cách:

Và sau đó thêm một unit test nữa để đảm bảo element h1 có chứa string cần thiết:

Bạn có thể thoải mái thử nghiệm với bản live demo để xem thử trước kết quả.

Trước khi đóng lại bài viết, hãy tìm hiểu tính năng nữa rất hay của Angular CLI.

Deploy đến GitHub Pages

Angular CLI giúp ta deploy ứng dụng lên GitHub Pages thật đơn giản, chỉ với một dòng lệnh duy nhất:

Lệnh github-pages:deploy sẽ yêu cầu Angular CLI xây dựng phiên bản ứng dụng tĩnh và push lên nhánh gh-pages` của GitHub repo:

Ứng dụng của chúng ta giờ đã có mặt trên .

Thật tuyệt phải không!?

Tóm tắt

Không còn nghi ngờ gì nữa, Angular 2 là một công cụ tốt, tốt đến đáng sợ!

Trong phạm vi bài viết, chúng ta đã tìm hiểu về:

  • Cách bắt đầu một ứng dụng Angular hoàn toàn mới với Angular CLI
  • Cách implement business logic trong Angular service và cách test business logic với unit tests
  • Cách dùng component để tương tác với user và cách ủy nhiện logic cho service thông qua dependency injection
  • Cấu trúc mẫu Angular cơ bản, da lông về cách làm việc của Angular dependency injection
  • Cuối cùng, chúng ta đã học được cách nhanh chóng deploy ứng dụng lên GitHub Pages

Trong phần tiếp theo, chúng ta sẽ tìm hiểu cách tạo components riêng biệt để hiển thị một loạt todo và chi tiết cho từng todo.

ITZone via sitepoint

Share the news now