How to make your Angular 8 forms reactive
Tags: angular, javascript, webdev
Published: 2019-10-04 13:14:54

---
title: How to make your Angular 8 forms reactive
published: true
tags: angular,javascript,webdev
canonical_url: https://blog.logrocket.com/how-to-make-your-angular-8-forms-reactive/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/ge6yuil68g0ov03mx9kv.png
---
**Written by [Nwose Lotanna](https://blog.logrocket.com/author/nwoselotanna/)**✏️

## Before you start

To be able to follow through in this article’s demonstration you should have:

- [Node version 11.0](https://nodejs.org/en/download/) installed on your machine.
- [Node Package Manager version 6.7](https://nodejs.org/en/download/) (this usually ships with Node installation)
- [Angular CLI](https://cli.angular.io/) version 8.0
- The latest version of [Angular (version 8)](https://cli.angular.io/)

```jsx
// run the command in a terminal
ng version
```

Confirm that you are using version 8, and update to 8 if you are not.

- Download this tutorial’s starter project [here](http://github.com/viclotana/ng_canvas) to follow through the demonstrations
- Unzip the project and initialize the node modules in your terminal with this command:

```jsx
npm install
```

Other things that will be nice-to-haves are:

- A working knowledge of the Angular framework at a beginner level
- Familiarity with the Angular constructor will be a plus but not a requirement

## Forms in Angular

Angular provides two main approaches to handling forms — the template-driven method and the model-driven method which involves reactive forms.

**The template method** is the default method of form handling in Angular where you have to use ng directives to build your form in the template. It is great for simple forms like basic contact forms in brand pages, it draws a lot of similarity to the old Angular JS way of form handling and implicitly creates concepts like form control behind the scenes. The other approach is the **reactive forms approach**.

## What are reactive forms?

Reactive forms are a platform for achieving the model-driven approach of form handling in Angular. It was introduced by Angular after the release of Angular 2. Although it is reportedly verbose, it is the most powerful and scalable way of form handling in Angular. As opposed to the template-driven forms that use template directives to build the skeleton of a form, reactive forms let you build out a form and react to the changes in the values inside the component class.

## Why are reactive forms important?

With reactive forms, you find out that it is easier to build cleaner forms as every JavaScript framework advises not to make the template clustered, this is a priority as the form logic now lies in the component class. Also, it reduces the need for using a lot of directives and even end-to-end testing as you can now easily test your forms. It also gives the developer all of the control and nothing is implicit anymore. Every choice about inputs and controls has to be made intentionally and, of course, explicitly.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## Demo

To set up a reactive form, we will go through a step-by-step journey with code illustrations on how to get started and build a simple job board application form. If you started reading this post from the start, you will have your starter project open in your VS Code. To start, open up a new terminal in VS Code and generate two new components for the forms:

```jsx
ng generate component Employer
ng generate component Employee
```

There are a few steps you need to take to get reactive forms set up in your Angular project. Let’s take a look.

## Registration of reactive forms

The very first step is to tell Angular you want to use reactive forms by importing the module and registering it under imports. Your `app.module.ts` file should look like this:

```jsx
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EmployerComponent } from './employer/employer.component';
import { EmployeeComponent } from './employee/employee.component';
@NgModule({
  declarations: [
    AppComponent,
    EmployerComponent,
    EmployeeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

## Form controls

Form controls are classes that can hold both the data values and the validation information of any form element, that is to say, every form input you have in a reactive form should be bound by a form control. They are the basic units that make up reactive forms.

To use form controls, you have to import the module into the component you want to create your reactive form in. Open your `employer.component.ts` file and copy this code block inside it:

```jsx
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms'
@Component({
  selector: 'app-employer',
  templateUrl: './employer.component.html',
  styleUrls: ['./employer.component.css']
})
export class EmployerComponent implements OnInit {
  position = new FormControl('');
constructor() { }
ngOnInit() {
  }
}
```

Here the form control was imported and inside the class it was instantiated with the constructor for position. To reflect it in the interface, you have ensured that you associate it with the input element in the template file.

```jsx
// copy into employer.component.html file
<label>
  Position
  <input type="text" [formControl]="position">
</label>
```

To display it, open your app.component.html file and paste in the code block below:

```jsx
<div style="text-align:center">
  <h2>Angular Job Board </h2>
  <app-employer></app-employer>
</div>
```

## Data binding in reactive forms

At this stage, you might not see any big difference between this and the normal template forms you are used to, but it starts to make a lot of sense when you want to start managing the data values you get from your form. For data interpolation recall how you will have to use the ng-bind directive to bind properties to values in the template, now all you have to do is to call the value and the reactive forms API will bind the data and display it for you.

```jsx
<label>
  Position
  <input type="text" [formControl]="position">
</label>
<p>
  Your response: {{ position.value }}
</p>
```

With just `property.value`, a snapshot of the data value at the given time is captured and displayed in the interface.

![angular job board demo](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2019/10/angularjobboard.gif?resize=495%2C210&ssl=1)

## Replacing a data value

There are a lot of more things you can achieve with the form control properties and methods inside the [reactive forms API](https://angular.io/guide/reactive-forms#reactive-forms-api). Let us look at updating a data value with new data. The aforementioned API provides a method called setValue() which is used to set data values for input elements. The syntax looks like this:

```jsx
callingFunction() {
 this. propertyName.setValue('new data value');
}
```

To implement it in your sample demo form, you will add a replace data button in the template to trigger the function so that the data value can be updated. In your `employer.component.ts` file, copy in the code block below:

```jsx
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms'
@Component({
  selector: 'app-employer',
  templateUrl: './employer.component.html',
  styleUrls: ['./employer.component.css']
})
export class EmployerComponent implements OnInit {
  position = new FormControl('');
constructor() { }
ngOnInit() {
  }
  callingFunction() {
    this.position.setValue('backend engineer');
   }
}
```

Now in the `employer.component.ts` file copy in the code block below:

```jsx
<label>
  Position
  <input type="text" [formControl]="position">
</label>
<p>
  Your response: {{ position.value }}
</p>
<p>
  <button (click)="callingFunction()">Replace Data</button>
</p>
```

You will see it seamlessly replaces the data value on click as you specified.

![replace data angular job board](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2019/10/replacedateangular.gif?resize=513%2C234&ssl=1)

## Conclusion

This is a “getting started” guide to using reactive forms in Angular, you were shown the various approaches of form handling (and the differences of the approaches). You were also shown how the reactive forms approach is important and more efficient and how it encourages writing cleaner code. Stay tuned on the blog as more about reactive forms in Angular will be posted soon.
* * * 
**Editor's note:** Seeing something wrong with this post? You can find the correct version [here](https://blog.logrocket.com/how-to-make-your-angular-8-forms-reactive/).

## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
[Try it for free](https://logrocket.com/signup/).
* * *
The post [How to make your Angular 8 forms reactive](https://blog.logrocket.com/how-to-make-your-angular-8-forms-reactive/) appeared first on [LogRocket Blog](https://blog.logrocket.com).