Introduction
In this article, we are going to explore the steps to add Reactive/Model-driven Forms in an Angular application and the advantages of using them in the application.
Overview
We can create forms in a reactive style in Angular. We need to create form control objects in a component class and should bind them with HTML form elements in the template. A component can observe the form of control state changes and react to them.
Here, we will be using FormBuilder class to create reactive forms, which have a simplified syntax. We need to import ReactiveFormsModule to create reactive forms. We can use built-in validators using the Validators class. For example, if we want to use the 'required' validator, it can be accessed as Validators.required.
Advantages of Reactive/Model-driven Forms
- We can listen to form changes or events easily using reactive forms. Each FormGroup or FormControl has few events like valueChanges, statusChanges, etc., which we can subscribe to.
- Model-driven forms are used in creating medium to large scale applications.
- We can now perform unit testing (using the Jasmine framework) on the validation logic as it is written inside a component class.
Demosteps
Open app.module.ts and below code to add a reactive form module:
- 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 {Form, FormsModule} from '@angular/forms';
- import { ArticleFormComponent } from './article-form/article-form.component';
- import { RegistrationFormComponent } from './registration-form/registration-form.component';
- @NgModule({
- declarations: [
- AppComponent,
- ArticleFormComponent,
- RegistrationFormComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,
- FormsModule,
- ReactiveFormsModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Create a component called RegistrationForm using the following CLI command.
Add the following code in the registration-form.component.ts file:
- import { Component, OnInit } from '@angular/core';
- import { FormBuilder, FormGroup, Validators } from '@angular/forms';
- @Component({
- selector: 'app-registration-form',
- templateUrl: './registration-form.component.html',
- styleUrls: ['./registration-form.component.css']
- })
- export class RegistrationFormComponent implements OnInit {
- registerForm: FormGroup;
- submitted : Boolean;
- constructor(private formBuilder: FormBuilder) { }
- ngOnInit() {
- this.registerForm = this.formBuilder.group({
- firstName: ['', Validators.required],
- lastName: ['', Validators.required],
- address: this.formBuilder.group({
- street: [],
- zip: [],
- })
- });
- }
- }
Line 2: Import FormBuilder class to create a reactive form. Also, import FormGroup class to create a group of form controls and Validators for validation.
Line 09:Create a property registerForm of type FormGroup.
Line 11: Inject a formBuilder instance using the constructor.
Line 12: Angular has some life cycle methods/hooks to provide visibility into key life moments of a component and the ability to act when they occur.ngOnInit is a lifecycle hook that will be invoked when Angular initializes the directive or component.
Line 13: formBuilder.group() method creates a FormGroup. It takes an object whose keys are FormControl names and values are their definitions.
Line 14-18: Create form controls such as firstName, lastName, and address as a subgroup with fields street, zip, and city. These fields are form controls. Configure built-in validators for each control using [' ', Validators.required] syntax where the first parameter is the default value for the control and the second parameter is an array of validations. If multiple validators are to be applied, then we should give it as [' ', [Validators.required,Validators.maxlength(10)]] .
Add the below code in registration-form.component.html:
- <div class="container">
- <h1>Registration Form</h1>
- <form [formGroup]="registerForm">
- <div class="form-group">
- <label>First Name</label>
- <input type="text" class="form-control" formControlName="firstName">
- <p *ngIf="registerForm.controls.firstName.errors" class="alert alert-danger">This field is required!</p>
- </div>
- <div class="form-group">
- <label>Last Name</label>
- <input type="text" class="form-control" formControlName="lastName">
- <p *ngIf="registerForm.controls.lastName.errors" class="alert alert-danger">This field is required!</p>
- </div>
- <div class="form-group">
- <fieldset formGroupName="address">
- <label>Street</label>
- <input type="text" class="form-control" formControlName="street">
- <label>Zip</label>
- <input type="text" class="form-control" formControlName="zip">
- <label>City</label>
- <input type="text" class="form-control" formControlName="city">
- </fieldset>
- </div>
- <button type="submit" (click)="submitted=true">Submit</button>
- </form>
- <br/>
- <div [hidden]="!submitted">
- <h3> Employee Details </h3>
- <p>First Name: {{ registerForm.get('firstName').value }} </p>
- <p> Last Name: {{ registerForm.get('lastName').value }} </p>
- <p> Street: {{ registerForm.get('address.street').value }}</p>
- <p> Zip: {{ registerForm.get('address.zip').value }} </p>
- </div>
- </div>
-
Line 27: the div tag will be hidden if the form is not submitted
Line 29-32: Using get() method of FormGroup, we are fetching values of each FormControl and rendering it
Add the below code in registration-form.component.css:
- .ng-valid[required] {
- border-left: 5px solid #42A948;
- }
- .ng-invalid:not(form) {
- border-left: 5px solid #a94442;
- }
Add below code in app.component.html:
- <app-registration-form></app-registration-form>
Now save the project and observe the output in the browser. You will get the below output screen:
It renders the values at the bottom after clicking the submit button, as shown below:
Summary
In this article, we explored the steps to add Reactive/Model-driven Forms in an Angular application and the advantages of using them. I hope you like the article. Until next time - Happy Reading
Cheers