Search⌘ K
AI Features

Data Input Using Reactive Forms

Explore how to build data input forms in Ionic using Angular's Reactive Forms approach. Understand how to programmatically define form controls, apply validation rules, and manage form state. Learn to provide real-time user feedback, handle input changes, and implement a structured workflow for reactive form development.

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 ...

TypeScript 3.3.4
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 ...