Using the NgForm directive

We already mentioned that the form directive enhances the HTML5 form’s behavior by adding some additional Angular 2-specific logic. Now, let’s take a step back and take a look at the form that surrounds the input elements:

<form #f="ngForm" (ngSubmit)="addDeveloper()"
      class="form col-md-4" [hidden]="submitted">
  …
</form>

In the preceding snippet, we defined a new identifier called f, which references to the form. We can think of the form as a composition of controls; we can access the individual controls through the form’s controls property. On top of this, the form has the touched, untouched, pristine, dirty, invalid, and valid properties, which depend on the individual controls defined within the form. For example, if none of the controls within the form has been touched, then the form itself is going to be with the status untouched. However, if any of the controls in the form has been touched at least once, the form will be with the status touched as well. Similarly the form will be valid only if all its controls are valid.

In order to illustrate the usage of the form element, let’s define a component with the selector control-errors, which shows the current errors for a given control. We can use it in the following way:

<label class="control-label" for="realNameInput">Real name</label>
<div>
  <input id="realNameInput" class="form-control" type="text"
     ngControl="realName" [(ngModel)]="developer.realName"
         required maxlength="50">
  <control-errors control="realName"
    [errors]="{
      'required': 'Real name is required',
      'maxlength': 'The maximum length of the real name is 50 characters'
      }"
   />
</div>

Notice that we’ve also added the maxlength validator to the realName control.

The control-errors element has the following properties:

  • control: Declares the name of the control we want to show errors for.
  • errors: Creates a mapping between control error and an error message.

Now add the following imports in add_developer.ts:

import {NgControl, NgForm} from 'angular2/common';
import {Host} from 'angular2/core';

In these imports, the NgControl class is the abstract class that represents the individual form components, NgForm represents the Angular forms, and Host is a parameter decorator related to the dependency injection mechanism

Here is a part of the component’s definition:

@Component({
  template: '<div>{{currentError}}</div>',
  selector: 'control-errors',
  inputs: ['control', 'errors']
})
class ControlErrors {
  errors: Object;
  control: string;
  constructor(@Host() private formDir: NgForm) {}
  get currentError() {…}
}