☰ See All Chapters |
Angular Forms
To simplify development, Angular provides a framework for creating, validating, and monitoring the fields of a form. With this API, each field of interest can be associated with a control, and each control can be associated with one or more validators. As the user enters text in the field, the framework automatically triggers the control's validators. In this manner, Angular provides the responsiveness of two-way data binding without sacrificing performance and reliability.
It uses the two-way data binding & event binding bind the form field to the Angular 2 component class. It tracks changes made to the form fields so that we can respond accordingly. The Angular forms provide the built-in validators to validate the inputs. You can create your own custom validator. It presents the validation errors to the user. Finally, it encapsulates all the input fields into an object structure when the user submits the form.
Angular provides two different ways of adding functionality to forms:
Template-driven forms
Changes to the form and component are configured using two-way binding. In Template driven approach is the easiest way to build the Angular 2 forms. The logic of the form is placed in the template. Template-driven forms in Angular 2 allows us to create sophisticated looking forms easily without writing any javascript code. The model-driven forms are created in component class, where Form fields are created as properties of our component class. This makes them easier to test.
Reactive forms (Model-driven)
All changes to the form and the component are managed in code using instances of FormGroup and FormControls. In Model driven approach, the logic of the form is placed in the component. The Model driven approach has more benefits as it makes the testing of the component easier. In this approach, the representation of the form is created in the component class. This form model is then bound to the HTML elements. This is done using the special markups.
Building Blocks of Angular 2 Forms
FormGroup , FormControl and FormArray are three Building blocks of Angular 2 Forms, irrespective of whether you are using Template driven or Forms Driven model. FormGroup , FormControl and FormArray all extend AbstractControl class.
To use these classes, an application's module needs to import ReactiveFormsModule from @angular/forms. Also, ReactiveFormsModule must be included in the imports array of the module's @NgModule decorator.
//app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './20simple_form_demo/app.component';
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
Before we start off, it is helpful to look at a trivial example that demonstrates how FormGroup and FormControls are used. The form in Figure below contains two text boxes and three buttons. When the first button is pressed, an 'a' is appended to the text in the first box. When the second button is pressed, a 'z' is appended to the text in the second box. When the third button is pressed, the form is submitted.
The code for this simple form creates one FormGroup for the form and two FormControls one for each text box. Listing below presents the code for the base component.
// app.component.ts import {Component} from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms';
@Component({ selector: 'app-tag', template: `
<form [formGroup]='group' (ngSubmit)='handleSubmit()'>
First Name:<input formControlName='firstName'><br /><br />
Last Name:<input formControlName='lastName'><br /><br />
<input type='button' (click)='changeFirstNameToUpperCase()' value='Change First Name To Uppercase'><br />
<input type='button' (click)='changeLastNameToUpperCase()' value='Change Last Name To Uppercase'><br /> <input type='submit' value='Submit'>
</form> `})
export class AppComponent { public group: FormGroup; constructor() { this.group = new FormGroup({ 'firstName': new FormControl('Manu'), 'lastName': new FormControl('Manjunatha') }); }
public changeFirstNameToUpperCase() { const control = this.group.get('firstName'); control.setValue(control.value.toUpperCase()); }
public changeLastNameToUpperCase() { const control = this.group.get('lastName'); control.setValue(control.value.toUpperCase()); }
public handleSubmit() { alert('Form submitted'); }; }
|
In the component's template, the <form> element sets the formGroup property to group. This tells Angular to associate the <form> element with the component's member named group, which is an instance of the FormGroup class. As we'll see, a FormGroup serves as a container of other form-related structures.
The component's template also contains two text boxes, and both <input> elements contain the formControlName property. This property is set to a value that corresponds to a FormControl member in the component class. The component reads and updates the element's text by accessing the associated FormControl.
All Chapters