When you want to manage your forms programmatically instead of relying purely on the template, reactive forms are the answer.
In this activity, you'll learn how to setup reactive forms.
-
Import
ReactiveForms
moduleIn
app.component.ts
, importReactiveFormsModule
from@angular/forms
and add it to theimports
array of the component.import { ReactiveFormsModule } from '@angular/forms';@Component({ selector: 'app-root', template: ` <form> <label>Name <input type="text" /> </label> <label>Email <input type="email" /> </label> <button type="submit">Submit</button> </form> `, imports: [ReactiveFormsModule],})
-
Create the
FormGroup
object with FormControlsReactive forms use the
FormControl
class to represent the form controls (e.g., inputs). Angular provides theFormGroup
class to serve as a grouping of form controls into a helpful object that makes handling large forms more convenient for developers.Add
FormControl
andFormGroup
to the import from@angular/forms
so that you can create a FormGroup for each form, with the propertiesname
andemail
as FormControls.import {ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';...export class AppComponent { profileForm = new FormGroup({ name: new FormControl(''), email: new FormControl(''), });}
-
Link the FormGroup and FormControls to the form
Each
FormGroup
should be attached to a form using the[formGroup]
directive.In addition, each
FormControl
can be attached with theformControlName
directive and assigned to the corresponding property. Update the template with the following form code:<form [formGroup]="profileForm"> <label> Name <input type="text" formControlName="name" /> </label> <label> Email <input type="email" formControlName="email" /> </label> <button type="submit">Submit</button></form>
-
Handle update to the form
When you want to access data from the
FormGroup
, it can be done by accessing the value of theFormGroup
. Update thetemplate
to display the form values:...<h2>Profile Form</h2><p>Name: {{ profileForm.value.name }}</p><p>Email: {{ profileForm.value.email }}</p>
-
Access FormGroup values
Add a new method to the component class called
handleSubmit
that you'll later use to handle the form submission. This method will display values from the form, you can access the values from the FormGroup.In the component class, add the
handleSubmit()
method to handle the form submission.handleSubmit() { alert( this.profileForm.value.name + ' | ' + this.profileForm.value.email );}
-
Add
ngSubmit
to the formYou have access to the form values, now it is time to handle the submission event and use the
handleSubmit
method. Angular has an event handler for this specific purpose calledngSubmit
. Update the form element to call thehandleSubmit
method when the form is submitted.<form [formGroup]="profileForm" (ngSubmit)="handleSubmit()">
And just like that, you know how to work with reactive forms in Angular.
Fantastic job with this activity. Keep going to learn about form validation.