Angular Reactive Typed Form

Angular Reactive Forms provide a powerful and flexible way to manage form input validation and data submission. With Reactive Forms, you can define form fields as objects, apply validation rules, and bind them to form controls in your template.

In this article, we'll look at how to create a typed reactive form in Angular. A typed form can help you catch errors at compile-time, rather than runtime, by ensuring that the correct data types are entered into your form fields.

Prerequisites

Before we begin, you should have a basic understanding of Angular and Reactive Forms. If you're unfamiliar with these topics, you can check out the official Angular documentation at the portal.

I have used the below tools to prepare this tutorial.

  • Angular CLI - 15.1.6
  • Node: 18.14.0
  • NPM – 9.3.1
  • Visual Studio Code

Without any delay, let us jump into the coding part.

The source code can be downloaded from GitHub

Creating a Typed Reactive Form

Let's start by creating a new Angular application using the Angular CLI. Open a terminal window in Visual Studio Code and enter the following command:

ng new Angular15App

This will create a new Angular application in a directory named "Angular15App". Change into the newly created directory and run the application using the following command:

cd Angular15App
ng serve

This will start the application and launch it in your web browser at http://localhost:4200.

Next, we will create a new component to host our typed reactive form. In the terminal window, enter the following command:

ng generate component typed-form

This will create a new " contact-form " component in the src/app directory. Open the component file at src/app/typed-form/typed-form.component.ts and add the following code:

import { Component, OnInit } from '@angular/core';
import {FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
    selector: 'app-typed-form',
    templateUrl: './typed-form.component.html',
    styleUrls: ['./typed-form.component.sass']
})
export class TypedFormComponent implements OnInit {
    ngOnInit(): void {}
    typedForm = new FormGroup({
        name: new FormControl('', Validators.required),
        email: new FormControl('', Validators.email),
        message: new FormControl('', Validators.required)
    });
    submittedData: string = "We are testing Reactive Typed Forms! ";
    constructor() {}
}

In this code, we're importing the necessary modules to work with Reactive Forms: FormGroup, FormControl, and Validators. We're also defining a new typedForm object of type FormGroup. This object represents our form and contains three FormControl objects: name, email, and message.

Each FormControl has a default value of an empty string ('') and an array of validation rules. The name field is required, as is the email field, which also needs to be a valid email address. The message field is also required.

In the typedForm object, we pass the three FormControl objects as key-value pairs. This associates each form control with its respective form field.

Binding the Typed Reactive Form to the Template

Now that we have our typed reactive form object, we must bind it to our template. Open the src/app/typed-form/typed-form.component.html file and add the following code:

<form (ngSubmit)="onSubmit()" [formGroup]="typedForm">
    <div>
        <label for="name">Name:</label>
        <input formControlName="name" id="name">
    </div>
    <div>
        <label for="email">Email:</label>
        <input formControlName="email" id="email">
    </div>
    <div>
        <label for="message">Message:</label>
        <textarea formControlName="message" id="message"></textarea>
    </div>
    <div>
        <button type="submit">Submit</button>
        <button type="reset" (click)="onResetSubmit()">Reset</button>
    </div>
</form>
<p>{{submittedData}}</p>

In this code, we use the FormGroup directive to bind the typedForm object to the form element. We are also using the formControlName directive to bind each FormControl object to its respective form field. The ngSubmit event is used to call the onSubmit() method when the form is submitted.

We also use the disabled attribute on the "Send" button to disable it when the form is invalid. This is done by checking the valid property of the typedForm object.

Handling Form Submissions

Finally, we add the onSubmit()and onResetSubmit() methods to our component. Open the src/app/typed-form/typed-form.component.ts file and add the following code:

onSubmit() {
    if (!this.typedForm.valid) {
        this.submittedData = "Mandatory Fields needs to be filled";
    } else {
        this.submittedData = `Name : ${this.typedForm.value.name}, Email : ${this.typedForm.value.email}, Message : ${this.typedForm.value.message}`;
    }
}
onResetSubmit() {
    this.typedForm.reset();
    this.submittedData = "We are testing Reactive Typed Forms!";
}

In this code, we're checking if the form is valid using the valid property of the typedForm object. We can submit the form data to the server if the form is valid. If the form is invalid, we display an error message on the browser.

We are good to test the code.

Enter the name, email, and message, and click on Submit. The message will be displayed as below.

Angular Reactive Typed Form

In this blog post, we explored the concept of Reactive Typed Forms in Angular and provided an example of how to implement them. Reactive Typed Forms provide several benefits over traditional template-driven forms, including strong typing, reactive programming, and built-in validation capabilities. Following the steps outlined above, developers can easily create Reactive Typed Forms in their Angular applications.

In addition to the basic implementation of Reactive Typed Forms, developers can use several advanced techniques to enhance their forms' functionality. For example, developers can use custom validators to validate user input or the valueChanges property to monitor real-time changes to the form values.

In conclusion, Reactive Typed Forms are a powerful feature of Angular that provide a more robust and reactive way of creating and managing forms in web applications. Using Reactive Typed Forms, developers can ensure type safety, improve user experience, and build more robust and scalable applications.