With Reactive Forms, our validation and binding are configured in the backing code rather than the markup. Today, we’ll take yesterday’s template-driven form and convert it to a reactive form, and in the process you can decide which style you like better.

You can always grab tagged source code on the GitHub repo which will be tagged day1, day2, etc.

You can Subscribe to my Fresh Bytecode channel for regular Java/Web-related screencasts, or if you’re just into Angular, checkout the YouTube Playlist where I update all the episodes in this series as they come out.

Here’s the script so you can follow along at home:

[ ] First, we’ll update our module list to import reactive forms

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

imports: [ BrowserModule, FormsModule, ReactiveFormsModule, routing, HttpModule,

[ ] We’ll update our template code to spark the form model

import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';

form = new FormGroup({
    username : new FormControl(),
    password : new FormControl(),
    rememberme : new FormControl()
  })

[ ] Remove all our ngModel directive

[ ] Wire our form to our model

<form class="ui form error" [formGroup]='form' 

name='username' becomes formControlName='username' etc

[ ] Test our form model

[ ] Add some validation logic

form = new FormGroup({
    username : new FormControl('',[ Validators.required] ),
    password : new FormControl('', [ Validators.required] ),
    rememberme : new FormControl(true)
  })

[ ] Refresh our validation logic

<div *ngIf='form.controls.username.invalid && form.controls.username.dirty' class="ui error message"><p>Username is a required field</p></div>

[ ] Refactor to use the FormBuilder DSL

  public form : FormGroup;

  constructor(private formBuilder : FormBuilder) { }

  ngOnInit() {

    this.form = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
      rememberme: [true],
    })

  }

[ ] Winning with reactive forms complete

[ ] Tomorrow we’ll tackle End to End testing