DEV Community

Cover image for How to manage reactive form controls with form groups in Angular 8
Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

How to manage reactive form controls with form groups in Angular 8

Written by Nwose Lotanna✏️

Why are reactive forms important?

With reactive forms, you will discover that it is easier to build cleaner forms. Because every JavaScript framework advises that you don’t make the template clustered, this has become a priority as the form logic now lies in the component class.

It also reduces the need to use a lot of directives and even end-to-end testing since you can now easily test your forms. It gives the developer all the control, and nothing is implicit anymore — every choice about inputs and controls must be made intentionally and, of course, explicitly.

In Angular, 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.

These are the basic units that make up reactive forms. In this article, you will be shown how form controls can be divided by form groups to create clusters to provide a platform to easily access the template element as groups.

LogRocket Free Trial Banner

What is a form group?

Form groups wrap a collection of form controls; just as the control gives you access to the state of an element, the group gives the same access but to the state of the wrapped controls. Every single form control in the form group is identified by name when initializing.

A FormGroup aggregates the values of each child FormControl into one object, with each control name as the key. It calculates its status by reducing the status values of its children.

Before you start…

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

  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (usually ships with the Node installation)
  • Angular CLI version 8.0
  • The latest version of Angular (version 8)
// run the command in a terminal
ng version
Enter fullscreen mode Exit fullscreen mode

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

  • Download the Augury Chrome extension here.
  • Download this tutorial’s starter project here to follow through the demonstrations.
  • Unzip the project and initialize the Node modules in your terminal with this command:
npm install
Enter fullscreen mode Exit fullscreen mode

Other things that would be nice to have are:

  • A working knowledge of the Angular framework at a beginner level.
  • Familiarity with form controls in Angular will be a plus but not a requirement.

Demo

To illustrate the concept of form groups, we will go through the process of building a reactive form so that you can fully grasp how to set it up with form groups. From here, we assume you have downloaded the starter project on GitHub and opened it in VS Code.

Registering form groups

The first thing to do is to tell Angular that you want to make use of the form group by importing it inside the appropriate component. Navigate to the employee.component.ts file and copy in the code block below:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    age: new FormControl('')
  });
constructor() { }
ngOnInit() {
  }
}
Enter fullscreen mode Exit fullscreen mode

Here the form group was both imported and initialized to group together some form controls that compose the bio section of the form. To reflect this group, you have to associate the model to the view with the form group name, like this:

// copy inside the employee.component.html file
<form [formGroup]="bioSection" (ngSubmit)="callingFunction()">

  <label>
    First Name:
    <input type="text" formControlName="firstName">
  </label>
<label>
    Last Name:
    <input type="text" formControlName="lastName">
  </label>
<label>
    Age:
    <input type="text" formControlName="age">
  </label>
<button type="submit">Submit Application</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Just like the form control, the form group name is used to identify the form group in the view, and on submit, the callingFunction will be triggered. Your app.component.html file should look like this:

<div style="text-align:center">
  <h2>Angular Job Board </h2>
  <app-employee></app-employee>
</div>
Enter fullscreen mode Exit fullscreen mode

Now run your application in development with the command:

ng serve
Enter fullscreen mode Exit fullscreen mode

It should look like this:

Angular Job Board Form

Nesting form groups

Yes, the reactive forms API makes it possible to nest a form group inside another form group. Copy the code block below into the employee.component.ts file:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    age: new FormControl(''),
    stackDetails: new FormGroup({
      stack: new FormControl(''),
      experience: new FormControl('')
    }),
    address: new FormGroup({
        country: new FormControl(''),
        city: new FormControl('')
    })
  });
constructor() { }
ngOnInit() {
  }
  callingFunction() {
    console.log(this.bioSection.value);
   }
}
Enter fullscreen mode Exit fullscreen mode

Here you see that the main form group wrapper is the bio section inside which both the stack details group and the address group is nested. It is important to note — as you see in the code block — that nested form groups are not defined by the assignment statement, but rather with the colon, just like you will a form control. Reflecting this in the view will look like this:

// copy inside the employee.component.html file
<form [formGroup]="bioSection" (ngSubmit)="callingFunction()">
    <h3>Bio Details
</h3>

  <label>
    First Name:
    <input type="text" formControlName="firstName">
  </label> <br>
<label>
    Last Name:
    <input type="text" formControlName="lastName">
  </label> <br>
<label>
    Age:
    <input type="text" formControlName="age">
  </label>
<div formGroupName="stackDetails">
    <h3>Stack Details</h3>

    <label>
      Stack:
      <input type="text" formControlName="stack">
    </label> <br>

    <label>
      Experience:
      <input type="text" formControlName="experience">
    </label>
  </div>
<div formGroupName="address">
    <h3>Address</h3>

    <label>
      Country:
      <input type="text" formControlName="country">
    </label> <br>

    <label>
      City:
      <input type="text" formControlName="city">
    </label>
  </div>
<button type="submit">Submit Application</button>
</form>
Enter fullscreen mode Exit fullscreen mode

It is very important that every name in the model and the view match — you do not misspell the form control names! When you save and run the application, if you do get any errors, read the error message and correct the misspelling you must have used. You can style your component with the style instructions below:

input[type=text] {
    width: 30%;
    padding: 8px 14px;
    margin: 2px;
    box-sizing: border-box;
  }
  button {
      font-size: 12px;
      margin: 2px;
      padding: 8px 14px;
  }
Enter fullscreen mode Exit fullscreen mode

If you run the application, you should see something like this in your browser:

Angular Job Board Form Bio

When you use the form and submit, you will see your input results returned in the browser console. The complete code to this tutorial can be found here on GitHub.

Conclusion

In addition to learning about form controls, you have now been introduced to the important concept of grouping these controls. You were also shown why grouping them is very important, as it ensures that their collective instances can be captured at once. The next concept we will be looking at is form builders, keep reading the blog!


Editor's note: Seeing something wrong with this post? You can find the correct version here.

Plug: LogRocket, a DVR for web apps

 
LogRocket Dashboard Free Trial Banner
 
LogRocket 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.


The post How to manage reactive form controls with form groups in Angular 8 appeared first on LogRocket Blog.

Top comments (0)