DEV Community

Cover image for A Practical Introduction to Reactive Forms in Angular
Ayush Agarwal
Ayush Agarwal

Posted on • Originally published at Medium

A Practical Introduction to Reactive Forms in Angular

Forms are an essential component of any web application or mobile application. Whether it is a login page, search bar, or filters, all involve using forms. They facilitate user interaction and data collection, making them a crucial part of the user experience.

In web applications, forms are of two types, Template Forms, and Reactive Forms. This blog will focus on exploring and understanding Reactive Forms in the context of Angular.

Introduction

This will be the first blog in our Reactive Forms in Angular Series. In this series, we will explore the power of reactive forms and how they can significantly enhance the form-handling capabilities of your Angular applications. You've come to the right place if you are new to or want to deepen your understanding.

Setting up the Project

Before jumping straight into forms, let’s ensure we have the basic project setup. Ensure you have Angular CLI installed. not, you can install it using npm. Once Angular CLI is ready, create a new Angular project using the following command:

  • Project Creation using Angular CLI
ng new my-reactive-forms-project
cd my-reactive-forms-project
Enter fullscreen mode Exit fullscreen mode

We must import and set up the necessary modules to use Reactive Forms in your project. Open the app.module.ts file and import the ReactiveFormsModule from @angular/forms:

import { ReactiveFormsModule } from '@angular/forms';
Enter fullscreen mode Exit fullscreen mode

Next, add ReactiveFormsModule to the imports array in the @NgModule decorator:

@NgModule({
  imports: [
    // other imports...
    ReactiveFormsModule
  ],
  // other declarations and providers...
})
export class AppModule { } 
Enter fullscreen mode Exit fullscreen mode

Generating the Login Form Component

To generate a new component for the login form, use the Angular CLI:

ng generate component login
Enter fullscreen mode Exit fullscreen mode

Importing the Login Form Component in app.component.html

Open the app.component.html file, and let's add the newly generated login component to the main app component's template:

<div> 
    <app-login>
    </app-login> 
</div>
Enter fullscreen mode Exit fullscreen mode

Creating the Login Form

We will keep things simple for this blog to help you understand better. Let us create a simple login form using reactive forms.

Login Component File

Now, let's work on the login form using Reactive Forms. Open the login.component.ts file and add the following code:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;

  ngOnInit() {
    this.loginForm = new FormGroup({
      email: new FormControl('', [Validators.required, Validators.email]),
      password: new FormControl('', Validators.required)
    });
  }

  onSubmit() {
    // Handle form submission here
    if (this.loginForm.valid) {
      console.log(this.loginForm.value);
      // Additional logic to authenticate user or 
      // perform other actions
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Note: Reactive forms in Angular revolve around two key classes: FormGroup and FormControl. A FormGroup represents a collection of form controls and a FormControl represents an individual form control, such as an input field.

In the code above, we use Angular's built-in Validators to apply form validation rules to the email and password fields.

  • Validators.required: This validator ensures that the field is mandatory and that the user must provide a value before submitting the form. If the user leaves the email or password field empty, this validator will trigger an error message.

  • Validators.email: This validator checks if the entered value in the email field is in a valid email format. If the user enters an invalid email address, this validator will display an error message.

Template Integration and Adding Validation Messages

Let's integrate the Reactive Form into the login.component.html template and display validation messages:

<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="email">Email:</label>
    <input type="email" id="email" formControlName="email">
    <div *ngIf="loginForm.get('email')?.invalid && loginForm.get('email')?.touched">
      <div *ngIf="loginForm.get('email')?.errors?.['required']">Email is required.</div>
      <div *ngIf="loginForm.get('email')?.errors?.['email']">Invalid email format.</div>
    </div>
  </div>
  <div>
    <label for="password">Password:</label>
    <input type="password" id="password" formControlName="password">
    <div *ngIf="loginForm.get('password')?.invalid && loginForm.get('password')?.touched">
      <div *ngIf="loginForm.get('password')?.errors?.['required']">Password is required.</div>
    </div>
  </div>
  <button type="submit" [disabled]="loginForm.invalid">Login</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Reactive Forms in Action

It's time to run our Angular application. Open a terminal or command prompt in the project root directory and execute the following command:

ng serve
Enter fullscreen mode Exit fullscreen mode

Once the build process is complete, you can access the application by navigating to http://localhost:4200/ in your web browser. You should now see the login form displayed on the page.

As you use the login form, it enforces the validation rules we set earlier. If you try to submit the form without entering valid email and password values, validation messages will guide you. Once you provide valid values, the submit button will enable login.

Conclusion

In this blog, our primary focus was introducing Reactive Forms in Angular and building a functional login form. We intentionally kept the CSS styling minimal to prioritize the core concepts.

In future blogs, we will dive deeper into custom validations, form submission handling, and dynamic forms and explore additional powerful features of Reactive Forms.

Lastly, Your support keeps me going, and I give my 100 percent to these blogs! If you’ve found value, consider fueling the blog with a coffee ☕️ donation at the below link.

Buy me a COFFEE!

Thank you! 🙏

Top comments (0)