The Intuitive Programmer

Test Driven Development: Angular Reactive Forms

Reactive forms: Learning by doing

I’ve been developing using Angular for over a year. One thing that I love about working with the framework is how logical it can appear. To the lay programmer, it might be overly rigorous and lacking in the flexibility that other development tools might have (think React). To me, I love the rigor that comes in understanding it because it does provide a stable productive working environment in my opinion.

Mapping your entity to your form

Once you have an idea of what it is you are wanting to build, doing so in Angular with the right pattern is trivial! Take for example this coffee form example below. We initialize a form group.

orderForm: FormGroup = new FormGroup({});

Then we set the fields appropriately. Not that we can set if a field is required as well as set the default value of the field programmatically.

ngOnInit(): void {
    this.orderForm = this.fb.group({
      // this maps to the name input field...the validator required denotes
      // that it is a required field!
      name: ['', Validators.required],
      // we set email to a blank field
      email: [''],
      // we set the default selection of item to the Coffee value
      item: ['Coffee', Validators.required],
      // we set the size of the order form to default to Small
      size: ['Small',Validators.required],
      // we set the notes to be blank
      notes: ['']
    })
}

The last part is to set the formControlNames appropriately on the template file. Notice how similar the form control names are to the actual input fields!

<input
        id="name-field"
        required
        formControlName="name"
        type="text"
        name="field1" class="field-divided">

Rinse and repeat

Developing intuition is a process that takes time. Angular does a great job of providing predictable patterns that can be intuited on when working with business logic of a varying nature. Here we can see how the OrderForm might be an entity that is stored on the back end and how it can easily be extended to expand on or enhance the functionality of the application.

Check out this repo to see a basic test set up for validating the prescence of the field and inputs. Try to expand on it!

https://github.com/developer-alvin-muniz/tdd-reactive-form

Cheers,

A