...

/

Data Input Using Reactive Forms

Data Input Using Reactive Forms

Learn how to create more advanced forms using Angular's FormBuilder class.

Reactive Forms

Another approach to developing forms with angular involves defining their structure from within the class instead of within the template. This approach, known as Reactive Forms, affords the following functionality:

  • Implements validation rules for input fields.
  • Updates the form UI to help guide user behavior (for example, disabling buttons where required input fields have not been completed and displaying error messages).
  • Listens for value changes on input fields.

Using Reactive Forms, we can programmatically build our forms and use that logic to control the input fields and form state in our templates.

Creating a new app

We start by creating a new project by running the following command:

ionic start advanced-form blank --type=angular

The home component

In the advanced-form/src/app/home/home.page.ts file, we make the following amendments (highlighted):

Press + to interact
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
public form: FormGroup;
public name: any;
/**
* Creates an instance of HomePage.
*/
constructor(public fb: FormBuilder) {
this.form = fb.group({
name : ['', [Validators.required, Validators.minLength(4)]],
email : ['', [Validators.required, Validators.email]],
platform : ['', Validators.required]
});
this.name = this.form.get('name');
this.name
.valueChanges
.subscribe((value: string) => {
console.log(`Entered name is ${value}`);
});
}
/**
* Logs the form data to the console
*/
public saveDetails(value: any): void {
console.dir(value);
}
}

On line 2, we import the following Angular Form related services:

  • FormBuilder
  • FormGroup
  • Validators

These will be used to manage the input field logic and validation functionality for the page template.

A FormGroup allows us to manage more than ...