Forms controls and form groups in Angular
Form controls are basically classes that can hold both the data values and the validation information of any form element, which means 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.
Form groups are constructs that basically 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.
Generating form controls
Setting up form controls, especially for very long forms, can quickly become both monotonous and stressful. Angular provides a helper service to solve this problem so that you can always obey the DRY concept of avoiding repetition. This service is called the form builder service.
Before we 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
Confirm that you are using version 8, and update to 8 if you are not.
- 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
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
In this tutorial, you will be taken through a code-along journey building a reactive form with the form builder. If you have followed this post from the start, you will have downloaded and opened the starter project in VS Code. If you open the employee.component.ts
, file it should look like this:
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);
}
}
You can see that every single form control — and even the form group that partitions it — is spelled out, so over time, you as the developer keep repeating yourself. The form builder helps to solve this efficiency problem. To use the form builder, you must first register it.
Registering the form builder
To register the form builder in a component, the first thing to do is import it from Angular forms:
import { FormBuilder } from ‘@angular/forms’;
The next step is to inject the form builder service, which is an injectable provider that comes with the reactive forms module. You can then use the form builder after injecting it. Navigate to the employee.component.ts
file and copy in the code block below:
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms'
@Component({
selector: 'app-employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
bioSection = this.fb.group({
firstName: [''],
lastName: [''],
age: [''],
stackDetails: this.fb.group({
stack: [''],
experience: ['']
}),
address: this.fb.group({
country: [''],
city: ['']
})
});
constructor(private fb: FormBuilder) { }
ngOnInit() {
}
callingFunction() {
console.log(this.bioSection.value);
}
}
This does exactly the same thing as the previous code block you saw at the start, but you can see there is a lot less code and more structure — and, thus, optimal usage of resources. Form builders not only help to make your reactive forms’ code efficient, but they are also important for form validation.
Form validation
Using reactive forms in Angular, you can validate your forms inside the form builders. Run your application in development with the command:
ng serve
You will discover that the form submits even when you do not input values into the text boxes. This can easily be checked with form validators in reactive forms. The first thing to do, as with all elements of reactive forms, is to import it from Angular forms.
import { Validators } from '@angular/forms';
You can now play around with the validators by specifying the form controls that must be filled in order for the submit button to be active. Copy the code block below into the employee.component.ts
file:
The last thing to do is to make sure the submit button’s active settings are set accordingly. Navigate to the employee.component.html
file and make sure the submit statement looks like this:
<button type=”submit” [disabled]=”!bioSection.valid”>Submit Application</button>
If you run your application now, you will see that if you do not set an input for first name, you cannot submit the form — isn’t that cool? There are many more cool form validation tips you can get from the official guide here.
Displaying input values and status
The last thing you should know is how to use the value and status properties to display, in real time, the input values of your reactive form and whether it can be submitted or not.
The reactive forms API lets you use the value and status properties on your form group or form controls in the template section. Open your employee.component.html
file and copy in the code block below:
<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" [disabled]="!bioSection.valid">Submit Application</button>
<p>
Real-time data: {{ bioSection.value | json }}
</p>
<p>
Your form status is : {{ bioSection.status }}
</p>
</form>
This displays both the value and the status for submission for you in the interface as you use the form. The complete code to this tutorial can be found here on GitHub.
Conclusion
This article gives an overview of the form builder and how it is a great efficiency enabler for form controls and form groups. It also shows how important it can be for handling form validation easily with reactive forms. Happy hacking!
Experience your Angular apps exactly how a user does
Debugging Angular applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Angular state and actions for all of your users in production, try LogRocket. https://logrocket.com/signup/LogRocket is like a DVR for web apps, recording literally everything that happens on your site including network requests, JavaScript errors, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.
The LogRocket NgRx plugin logs Angular state and actions to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.
Modernize how you debug your Angular apps - Start monitoring for free.
No comments:
Post a Comment