Reader small image

You're reading from  Getting Started with Angular - Second edition - Second Edition

Product typeBook
Published inFeb 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781787125278
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Minko Gechev
Minko Gechev
author image
Minko Gechev

Minko Gechev is a software engineer who strongly believes in open source software. He has developed numerous such projects including codelyzer, the AngularJS style guide, aspect.js and many others, and is one of the coauthors of the official Angular style guide.
Read more about Minko Gechev

Right arrow

Chapter 6. Working with the Angular Router and Forms

By now, we're already familiar with the core of the framework. We know how to define components and directives in order to develop the view of our applications. We also know how to encapsulate business-related logic into services and wire everything together with the DI mechanism of Angular.

In this chapter, we'll explain a few more concepts that will help us build real-life Angular applications. They are as follows:

  • The component-based router of the framework.

  • Using Angular's forms module.

  • Developing custom form validators.

  • Developing template-driven forms.

Let's begin!

Developing the "Coders repository" application


Throughout the process of explaining the listed concepts, we'll develop a sample application that contains a repository of developers. Before we start coding, let's discuss the structure of the application.

The "Coders repository" will allow its users to add developers, either by filling a form with details about them, or by providing the GitHub handle for the developer and importing their profile from GitHub.

Note

For the purpose of this chapter, we will store information about the developers in memory, which means that, after the page is refreshed, we'll lose all the data stored during the session.

The application will have the following views:

  • A list of all the developers.

  • A view for adding or importing new developers.

  • A view that shows the given developer's details. This view has two subviews:

    • Basic details: Shows the name of the developer and their GitHub avatar if available.

    • Advanced profile: Shows all the details known of the developer.

The...

Exploring the Angular router


As we already know, in order to bootstrap any Angular application, we need to develop a root NgModule and a bootstrap component. The "Coders repository" application is not any different; the only addition in this specific case is that we will have multiple pages that need to be connected together with the Angular router.

Let's start with the imports required for the router's configuration and define the root component right after this:

// ch6/ts/step-0/app.ts
 
import {
  APP_BASE_HREF,
  LocationStrategy,
  HashLocationStrategy
} from '@angular/common';

import {RouterModule} from '@angular/router';

In the preceding snippet, we import the RouterModule directly from @angular/router; as we can see, the router is externalized outside the framework's core. This module declares all the routing-specific directives, as well as all the routing-related providers, which means that, if we import it, we'll get access to all of...

Using Angular's forms module


Now, let's continue with the implementation of the application. For the next step, we'll work on the AddDeveloper and Home components. You can continue your implementation by extending what you currently have in ch6/ts/step-0, or if you haven't reached step 1 yet, you can keep working on the files in ch6/ts/step-1.

Angular offers two ways of developing forms with validation:

  • A template-driven approach: This provides a declarative API where we declare the validations into the template of the component.

  • A model-driven approach (also known as reactive forms): This provides an imperative, reactive API.

Let's start with the template-driven approach for now and explore the model-driven approach in the next chapter.

Developing template-driven forms

Forms are essential for each CRUD (Create Retrieve Update and Delete) application. In our case, we want to build a form for entering the details of the developers we want to store.

By the end of this section, we'll have a form...

Two-way data binding with Angular


One of the most famous rumors about Angular 2 was that the two-way data binding functionality was removed because of the enforced unidirectional data flow. This is not exactly true; the Angular's form module implements a directive with the selector [(ngModel)] (we'll also refer to this directive as NgModel, because of the name of its controller), which allows us to easily achieve data binding in two directions: from the view to the model and from the model to the view.

Let's take a look at the following simple component:

// ch6/ts/simple-two-way-data-binding/app.ts 
 
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';

@Component({
 selector: 'app',
 template: `
  <input type="text" [(ngModel)]="name">
  <div>{{name}}...

Storing the form data


Let's peek at the interface of the AddDeveloper component's controller again:

export class AddDeveloper { 
  submitted: false; 
  successMessage: string; 
  developer = new Developer(); 
  //... 
  constructor(private developers: DeveloperCollection) {} 
  addDeveloper(form) {...} 
} 

It has a field of the Developer type, and we bind the form controls to its properties using the NgModel directive. The class also has a method called addDeveloper, which is being invoked on the submission of the form. We declare this by binding to the ngSubmit event using:

<!-- ch6/ts/multi-page-template-driven/add_developer.html --> 
<form #f="form" (ngSubmit)="addDeveloper()" 
      class="form col-md-4" [hidden]="submitted"> 
  ... 
  <button class="btn btn-default" 
      type="submit" [disabled]="!f.form.valid">Add</button> 
</form> 

In the preceding snippet, we can note two more...

Listing all the stored data


Now that we can add a new entry to the developers' collection, let's show a list of all the developers on the front page of the "Coders repository".

Open the file ch6/ts/step-1/home.ts (or step-2, depending on your progress during the past section), and enter the following content:

import {Component} from '@angular/core'; 
import {DeveloperCollection} from './developer_collection'; 
 
@Component({ 
  selector: 'home', 
  templateUrl: './home.html' 
}) 
export class Home { 
  constructor(private developers: DeveloperCollection) {}
 
  getDevelopers() { 
    return this.developers.getAll(); 
  } 
} 

There is nothing new to us here. We extend the functionality of the Home component by providing an external template and implementing the getDevelopers method, which delegates its call to the instance of DeveloperCollection that is injected in the constructor.

The template itself is something that we...

Summary


So far, we have explained the basics of routing in Angular. We took a look at how we can define different routes and implement the components associated with them that are displayed on route change. In order to link to the different routes, we introduced routerLink, and we also used the router-outlet directives for pointing out where the components associated with the individual routes should be rendered.

Another thing we took a look at was the Angular forms functionality with built-in and custom validation. After this, we explained the NgModel directive, which provides us with two-way data binding.

In the next chapter, we will cover how we can develop model-driven forms, child and parameterized routes, use the Http module for making RESTful calls, and transform data with custom pipes.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Getting Started with Angular - Second edition - Second Edition
Published in: Feb 2017Publisher: PacktISBN-13: 9781787125278
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Minko Gechev

Minko Gechev is a software engineer who strongly believes in open source software. He has developed numerous such projects including codelyzer, the AngularJS style guide, aspect.js and many others, and is one of the coauthors of the official Angular style guide.
Read more about Minko Gechev