Tuesday, March 14, 2017

Understanding Component Architecture: Refactoring an Angular App

Angular Component Architecture

This article is part 2 of the SitePoint Angular 2+ Tutorial on how to create a CRUD App with the Angular CLI.

In part one we learned how to get our Todo application up and running and deploy it to GitHub pages. This worked just fine, but unfortunately the whole app was crammed into a single component.

In this article (part two) we will examine a more modular component architecture. We will look at how to break this single component into a structured tree of smaller components that are easier to understand, re-use and maintain.

You don't need to have followed part one of this tutorial, for part two to make sense. You can simply grab a copy of our repo, checkout the code from part one, and use that as a starting point. This is explained in more detail below.

A Quick Recap

So let's look at what we covered in part one in slightly more detail. We learned how to:

  • initialize our Todo application using the Angular CLI
  • create a Todo class to represent individual todos
  • create a TodoDataService service to create, update and remove todos
  • use the AppComponent component to display the user interface
  • deploy our application to GitHub pages

The application architecture of part 1 looked like this:

Application Architecture

The components we discussed are marked with a red border.

In this second article we will delegate some of the work that AppComponent is doing to smaller components that are easier to understand, re-use and maintain.

We will create:

  • a TodoListComponent to display a list of todo's
  • a TodoListItemComponent to display a single todo
  • a TodoListHeaderComponent to create a new todo
  • a TodoListFooterComponent to show how many todo's are left

Application Architecture

By the end of this article, you will understand:

  • the basics of Angular component architecture
  • how you can pass data into a component using property bindings
  • how you can listen for events emitted by a component using event listeners
  • why it is a good practice to split components into smaller reusable components
  • the difference between smart and dumb components and why keeping components dumb is a good practice

So let's get started!

Up and Running

The first thing you will need to follow along with this article is the latest version of the Angular CLI. You can install this with the following command:

npm install -g @angular/cli@latest

If you need to remove a previous version of of the Angular CLI, here's how:

npm uninstall -g @angular/cli angular-cli
npm cache clean
npm install -g @angular/cli@latest

After that you'll need a copy of the code from part one. This is available at http://ift.tt/2mpeXuK. Each article in this series has a corresponding tag in the repository so you can switch back and forth between the different states of the application.

The code that we ended with in part one and that we start with in this article is tagged as part-1. The code that we end this article with is tagged as part-2.

You can think of tags like an alias to a specific commit id. You can switch between them using git checkout. You can read more on that here.

So, to get up and running (the the latest version of the Angular CLI installed) we would do:

git clone git@github.com:sitepoint-editors/angular-todo-app.git
cd angular-todo-app
npm install
git checkout part-1
ng serve

Then visit http://localhost:4200/. If all is well, you should see the working Todo app.

The Original AppComponent

Let's open src/app/app.component.html and have a look at the AppComponent that we finished with in part one:

<section class="todoapp">
  <header class="header">
    <h1>Todos</h1>
    <input class="new-todo" placeholder="What needs to be done?" autofocus="" [(ngModel)]="newTodo.title" (keyup.enter)="addTodo()">
  </header>
  <section class="main" *ngIf="todos.length > 0">
    <ul class="todo-list">
      <li *ngFor="let todo of todos" [class.completed]="todo.complete">
        <div class="view">
          <input class="toggle" type="checkbox" (click)="toggleTodoComplete(todo)" [checked]="todo.complete">
          <label></label>
          <button class="destroy" (click)="removeTodo(todo)"></button>
        </div>
      </li>
    </ul>
  </section>
  <footer class="footer" *ngIf="todos.length > 0">
    <span class="todo-count"><strong></strong>  left</span>
  </footer>
</section>

and its corresponding class in src/app/app.component.ts:

import {Component} from '@angular/core';
import {Todo} from './todo';
import {TodoDataService} from './todo-data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [TodoDataService]
})
export class AppComponent {

  newTodo: Todo = new Todo();

  constructor(private todoDataService: TodoDataService) {
  }

  addTodo() {
    this.todoDataService.addTodo(this.newTodo);
    this.newTodo = new Todo();
  }

  toggleTodoComplete(todo: Todo) {
    this.todoDataService.toggleTodoComplete(todo);
  }

  removeTodo(todo: Todo) {
    this.todoDataService.deleteTodoById(todo.id);
  }

  get todos() {
    return this.todoDataService.getAllTodos();
  }

}

Although our AppComponent works fine technically, keeping all code in one big component does not scale well and is not recommended.

Adding more features to our Todo application would make the AppComponent larger and more complex, making it harder to understand and maintain.

Therefore it is recommended to delegate functionality to smaller components. Ideally the smaller components should be configurable so that we don't have to rewrite their code when the business logic changes.

For example: in part three of this series, we will update the TodoDataService to communicate with a REST API and we want to make sure that we will not have to change any of the smaller components when we refactor the TodoDataService.

If we look at the AppComponent template we can extract its underlying structure as:

<!-- header that lets us create new todo -->
<header></header>

<!-- list that displays todos -->
<ul class="todo-list">

    <!-- list item that displays single todo -->
    <li>Todo 1</li>

    <!-- list item that displays single todo -->
    <li>Todo 2</li>
</ul>

<!-- footer that displays statistics -->
<footer></footer>

If we translate this structure to Angular component names, we get:

<!-- TodoListHeaderComponent that lets us create new todo -->
<app-todo-list-header></app-todo-list-header>

<!-- TodoListComponent that displays todos -->
<app-todo-list>

    <!-- TodoListItemComponent that displays single todo -->
    <app-todo-list-item></app-todo-list-item>

    <!-- TodoListItemComponent that displays single todo -->
    <app-todo-list-item></app-todo-list-item>
</app-todo-list>

<!-- TodoListFooterComponent that displays statistics -->
<app-todo-list-footer></app-todo-list-footer>

Let's see how we can use the power of Angular's component driven development to make this happen.

A More Modular Component Architecture — Creating the TodoListHeaderComponent

Let's start by creating the TodoListHeader component.

From the root of our project, we use Angular CLI to generate the component for us:

$ ng generate component todo-list-header

which generates the following files for us:

create src/app/todo-list-header/todo-list-header.component.css
create src/app/todo-list-header/todo-list-header.component.html
create src/app/todo-list-header/todo-list-header.component.spec.ts
create src/app/todo-list-header/todo-list-header.component.ts

and automatically adds TodoListHeaderComponent to the AppModule declarations:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

// Automatically imported by Angular CLI
import { TodoListHeaderComponent } from './todo-list-header/todo-list-header.component';

@NgModule({
  declarations: [
    AppComponent,

    // Automitically added by Angular CLI
    TodoListHeaderComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Adding a component to the module declarations is required to make sure that all view templates in the module can use it the component. Angular CLI conveniently added TodoListHeaderComponent for us so we don't have to add it manually.

If TodoListHeaderComponent was not in the declarations and we used it in a view template, Angular would throw the following error:

Error: Uncaught (in promise): Error: Template parse errors:
'app-todo-list-header' is not a known element:
1. If 'app-todo-list-header' is an Angular component, then verify that it is part of this module.
2. If 'app-todo-list-header' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.

To learn more about module declarations, make sure to check out the Angular Module FAQ.

Now that we have all files generated for our new TodoListHeaderComponent, we can move the <header> element from src/app/app.component.html to src/app/todo-list-header/todo-list-header.component.html:

<header class="header">
  <h1>Todos</h1>
  <input class="new-todo" placeholder="What needs to be done?" autofocus="" [(ngModel)]="newTodo.title"
         (keyup.enter)="addTodo()">
</header>

and add the corresponding logic to src/app/todo-list-header/todo-list-header.component.ts:

import { Component, Output, EventEmitter } from '@angular/core';
import { Todo } from '../todo';

@Component({
  selector: 'app-todo-list-header',
  templateUrl: './todo-list-header.component.html',
  styleUrls: ['./todo-list-header.component.css']
})
export class TodoListHeaderComponent {

  newTodo: Todo = new Todo();

  @Output()
  add: EventEmitter<Todo> = new EventEmitter();

  constructor() {
  }

  addTodo() {
    this.add.emit(this.newTodo);
    this.newTodo = new Todo();
  }

}

Instead of injecting the TodoDataService in our new TodoListHeaderComponent to save the new todo, we emit an add event and pass the new todo as an argument.

We already learned that the Angular template syntax allows us to attach a handler to an event. For example, the following code:

Continue reading %Understanding Component Architecture: Refactoring an Angular App%


by Jurgen Van de Moere via SitePoint

No comments:

Post a Comment