Skip to main content

Reactive Forms

Reactive forms in Angular provide a model-driven approach to handling form inputs whose values change over time. This tutorial will cover the fundamental concepts of reactive forms, including how to create and update them.

What Are Reactive Forms?

Reactive forms are a way to create and manage forms in Angular in a reactive style. This means that instead of writing code to manually update the value of a form input, you can use reactive forms to create a form model with a fixed structure and use observables to watch for changes in the form's value.

Creating a Reactive Form

To use reactive forms in Angular, you'll first need to import the ReactiveFormsModule from @angular/forms in your module.

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
imports: [
ReactiveFormsModule,
],
})
export class AppModule { }

Then, in your component, you can create a new form by instantiating a FormGroup object, which represents a group of FormControl instances.

import { FormGroup, FormControl } from '@angular/forms';

export class ProfileEditorComponent {
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
});
}

Each key in the object passed to the FormGroup constructor is the name of a control, and the value is a new instance of FormControl, which represents a single input field.

Binding the Form to the Template

To bind this form to the template, you can use the [formGroup] directive.

<form [formGroup]="profileForm">

<label>
First Name:
<input type="text" formControlName="firstName">
</label>

<label>
Last Name:
<input type="text" formControlName="lastName">
</label>

</form>

The formControlName directive binds each individual input to its corresponding FormControl instance.

Accessing Form Data

You can access the data in your form using the value property of your FormGroup instance.

submit() {
console.log(this.profileForm.value);
}

Handling Form Submission

To handle form submission, you can use Angular's event binding to bind to the ngSubmit event.

<form [formGroup]="profileForm" (ngSubmit)="submit()">
<!-- form controls -->
<button type="submit">Submit</button>
</form>

In the component, define the submit method to handle the form submission.

submit() {
console.log(this.profileForm.value);
}

When the form is submitted, Angular will call the submit method and log the form value.

Conclusion

That's it! You now have a basic understanding of how to create and use reactive forms in Angular. Remember, reactive forms provide a more flexible way to manage form state through streams. With reactive forms, you can manage the form and validation updates with precision and efficiency.