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:

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

    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:

    onSubmit() {
      console.log(this.user);
    }

    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:

    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    
    @Component({
      selector: 'app-root',
      template: `
        <form [formGroup]="userForm" (ngSubmit)="onSubmit()">
          <label>Name:</label>
          <input type="text" formControlName="name">
          <label>Email:</label>
          <input type="email" formControlName="email">
          <button type="submit">Submit</button>
        </form>
      `
    })
    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);
      }
    }

    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:

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

    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:

    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    
    @Component({
      selector: 'app-root',
      template: `
        <form [formGroup]="userForm" (ngSubmit)="onSubmit()">
          <label>Name:</label>
          <input type="text" formControlName="name">
          <p *ngIf="userForm.get('name').invalid && userForm.get('name').touched">Invalid Name</p>
          <label>Email:</label>
          <input type="email" formControlName="email">
          <p *ngIf="userForm.get('email').invalid && userForm.get('email').touched">Invalid Email</p>
          <button type="submit">Submit</button>
        </form>
      `
    })
    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);
      }
    }

    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 <p> 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.

    © 2023 Designed & Developed by José Matos.