Reactive Forms Basics

To begin, we must first ensure we are working with the right directives and the right classes in order to take advantage of procedural forms. For this, we need to ensure that the ReactiveFormsModule was imported in the bootstrap phase of the application module.

This will give us access to components, directives and providers like FormBuilder, FormGroup, and FormControl

In our case, to build a login form, we're looking at something like the following:

app/login-form.component.ts

  1. import { Component } from '@angular/core';
  2. import { FormGroup, FormControl, FormBuilder } from '@angular/forms';
  3. @Component({
  4. selector: 'app-root',
  5. templateUrl: 'app/app.component.html'
  6. })
  7. export class AppComponent {
  8. username = new FormControl('')
  9. password = new FormControl('')
  10. loginForm: FormGroup = this.builder.group({
  11. username: this.username,
  12. password: this.password
  13. });
  14. constructor(private builder: FormBuilder) { }
  15. login() {
  16. console.log(this.loginForm.value);
  17. // Attempt Logging in...
  18. }
  19. }

app/login-form.component.html

  1. <form [formGroup]="loginForm" (ngSubmit)="login()">
  2. <label for="username">username</label>
  3. <input type="text" name="username" id="username" [formControl]="username">
  4. <br>
  5. <label for="password">password</label>
  6. <input type="password" name="password" id="password" [formControl]="password">
  7. <br>
  8. <button type="submit">log in</button>
  9. </form>

View Example

FormControl

Note that the FormControl class is assigned to similarly named fields, both on this and in the FormBuilder#group({ }) method.This is mostly for ease of access.By saving references to the FormControl instances on this, you can access the inputs in the template without having to reference the form itself.The form fields can otherwise be reached in the template by using loginForm.controls.username and loginForm.controls.password.Likewise, any instance of FormControl in this situation can access its parent group by using its .root property (e.g. username.root.controls.password).

Make sure that root and controls exist before they're used.

A FormControl requires two properties: an initial value and a list of validators.Right now, we have no validation. This will be added in the next steps.

原文: https://angular-2-training-book.rangle.io/handout/forms/reactive-forms/reactive-forms_basics.html