Handling Form Submission in Angular with Examples
Tags: webdev, angular, typescript, form
Published: 2023-05-23 06:00:01

## Handling Form Submission in Angular with Examples



Forms are an integral part of any web application and Angular provides a robust set of APIs to handle forms with ease. In this article, we will explore how to handle form submission in Angular and provide practical examples of how to implement forms in your Angular application.

### Angular Forms Overview



Angular provides two types of forms to handle user input. The first is template-driven, which relies on two-way data binding and directives to handle form input. The second is reactive forms, which is a more flexible and scalable approach to handling user input.

In template-driven forms, the `ngForm` directive is used to create a form group and `ngModel` is used to bind form controls to input values. Reactive forms, on the other hand, use the `FormGroup` and `FormControl` classes to create a more structured form group and individual form controls.

### Handling Form Submission in Angular



Handling form submission in Angular is accomplished using the `(ngSubmit)` event. This event is fired when a form is submitted and allows developers to handle form data in a structured manner.

Let's start by creating a template-driven form in Angular:

<pre><code>&lt;form (ngSubmit)="onSubmit()"&gt;
  &lt;label&gt;Name:&lt;/label&gt;
  &lt;input type="text" name="name" [(ngModel)]="user.name"&gt;
  &lt;label&gt;Email:&lt;/label&gt;
  &lt;input type="email" name="email" [(ngModel)]="user.email"&gt;
  &lt;button type="submit"&gt;Submit&lt;/button&gt;
&lt;/form&gt;</code></pre>

In this example, we have a simple form that collects user name and email address. When the form is submitted, the `onSubmit()` method is called:

<pre><code>onSubmit() {
  console.log(this.user);
}</code></pre>

This method simply logs the form data to the console. If we were building a full-fledged application, we would likely perform some sort of API call or data manipulation here.

Reactive forms use a similar approach to handle form submission:

<pre><code>import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  template: `
    &lt;form [formGroup]="userForm" (ngSubmit)="onSubmit()"&gt;
      &lt;label&gt;Name:&lt;/label&gt;
      &lt;input type="text" formControlName="name"&gt;
      &lt;label&gt;Email:&lt;/label&gt;
      &lt;input type="email" formControlName="email"&gt;
      &lt;button type="submit"&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
  `
})
export class AppComponent {
  userForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.userForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]]
    });
  }

  onSubmit() {
    console.log(this.userForm.value);
  }
}</code></pre>

In this example, we first import the `FormBuilder`, `FormGroup`, and `Validators` classes from `@angular/forms`. We then create the `userForm` form group using the `FormBuilder` and define the `name` and `email` form controls with their respective validators.

When the form is submitted, the `onSubmit()` method is called, which logs the form data to the console.

### Validation in Angular Forms



Validation in Angular forms is an important aspect of ensuring that user input is valid and meets certain criteria. Angular provides a variety of validators that can be used to enforce validation rules on form controls.

Let's start by creating a template-driven form with validation:

<pre><code>&lt;form (ngSubmit)="onSubmit()"&gt;
  &lt;label&gt;Name:&lt;/label&gt;
  &lt;input type="text" name="name" [(ngModel)]="user.name" required minlength="2" maxlength="20"&gt;
  &lt;label&gt;Email:&lt;/label&gt;
  &lt;input type="email" name="email" [(ngModel)]="user.email" required email&gt;
  &lt;button type="submit"&gt;Submit&lt;/button&gt;
&lt;/form&gt;</code></pre>

In this example, we have added the `required`, `minlength`, `maxlength`, and `email` validators to the form controls. This ensures that the user must enter a name and email address that meet the required criteria.

Reactive forms use a similar approach to validation:

<pre><code>import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  template: `
    &lt;form [formGroup]="userForm" (ngSubmit)="onSubmit()"&gt;
      &lt;label&gt;Name:&lt;/label&gt;
      &lt;input type="text" formControlName="name"&gt;
      &lt;p *ngIf="userForm.get('name').invalid &amp;&amp; userForm.get('name').touched"&gt;Invalid Name&lt;/p&gt;
      &lt;label&gt;Email:&lt;/label&gt;
      &lt;input type="email" formControlName="email"&gt;
      &lt;p *ngIf="userForm.get('email').invalid &amp;&amp; userForm.get('email').touched"&gt;Invalid Email&lt;/p&gt;
      &lt;button type="submit"&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
  `
})
export class AppComponent {
  userForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.userForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      email: ['', [Validators.required, Validators.email]]
    });
  }

  onSubmit() {
    console.log(this.userForm.value);
  }
}</code></pre>

In this example, we have added the same validation rules to the `name` and `email` form controls using the `Validators` class. We have also added a `` element to display validation errors if the form control is invalid and has been touched.

### Conclusion



Handling form submission in Angular is a crucial part of any web application. Angular's robust set of APIs and directives make handling forms a breeze, from template-driven to reactive forms. By leveraging Angular's validation framework, developers can ensure that user input is valid and conforms to certain criteria.

Whether you are building a simple form or a complex data-driven application, Angular provides the tools you need to handle form submission with ease.