Written by: Geoffrey Callaghan

Forms in Angular

Forms In Angular

Creating forms in Angular involves using Angular’s powerful form handling capabilities. Angular provides two approaches to handle forms: Template-driven forms and Reactive forms. Reactive forms provide a more robust and scalable way to handle complex form requirements.

Here’s a step-by-step guide to creating forms using Angular Reactive Forms.

Step 1: Setting up the Project

  1. Create a new Angular project:

    ng new my-form-app
    cd my-form-app
  2. Install Angular Material (optional, for UI components):

    ng add @angular/material

Step 2: Create a Form Component

  1. Generate a new component:

    ng generate component my-form
  2. Add ReactiveFormsModule to your AppModule:

    // src/app/app.module.ts
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { ReactiveFormsModule } from '@angular/forms';
    import { AppComponent } from './app.component';
    import { MyFormComponent } from './my-form/my-form.component';
    
    @NgModule({
      declarations: [
        AppComponent,
        MyFormComponent
      ],
      imports: [
        BrowserModule,
        ReactiveFormsModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

Step 3: Define the Form Model

  1. Import necessary modules in your form component:

    // src/app/my-form/my-form.component.ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    
    @Component({
      selector: 'app-my-form',
      templateUrl: './my-form.component.html',
      styleUrls: ['./my-form.component.css']
    })
    export class MyFormComponent {
      myForm: FormGroup;
    
      constructor(private fb: FormBuilder) {
        this.myForm = this.fb.group({
          name: ['', Validators.required],
          email: ['', [Validators.required, Validators.email]],
          age: [null, [Validators.required, Validators.min(1)]]
        });
      }
    
      onSubmit() {
        if (this.myForm.valid) {
          console.log(this.myForm.value);
        }
      }
    }
  2. Create the template for the form:

    <!-- src/app/my-form/my-form.component.html -->
    <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
      <div>
        <label for="name">Name</label>
        <input id="name" formControlName="name">
        <div *ngIf="myForm.get('name')?.invalid && myForm.get('name')?.touched">
          Name is required
        </div>
      </div>
    
      <div>
        <label for="email">Email</label>
        <input id="email" formControlName="email">
        <div *ngIf="myForm.get('email')?.invalid && myForm.get('email')?.touched">
          <span *ngIf="myForm.get('email')?.errors?.['required']">Email is required</span>
          <span *ngIf="myForm.get('email')?.errors?.['email']">Invalid email address</span>
        </div>
      </div>
    
      <div>
        <label for="age">Age</label>
        <input id="age" type="number" formControlName="age">
        <div *ngIf="myForm.get('age')?.invalid && myForm.get('age')?.touched">
          <span *ngIf="myForm.get('age')?.errors?.['required']">Age is required</span>
          <span *ngIf="myForm.get('age')?.errors?.['min']">Age must be greater than zero</span>
        </div>
      </div>
    
      <button type="submit" [disabled]="myForm.invalid">Submit</button>
    </form>

Step 4: Styling the Form

  1. Add some basic styles:

    /* src/app/my-form/my-form.component.css */
    form {
      max-width: 400px;
      margin: 0 auto;
    }
    
    div {
      margin-bottom: 15px;
    }
    
    label {
      display: block;
      margin-bottom: 5px;
    }
    
    input {
      width: 100%;
      padding: 8px;
      box-sizing: border-box;
    }
    
    div div {
      color: red;
      font-size: 0.8em;
    }
    
    button {
      padding: 10px 15px;
      background-color: #007bff;
      border: none;
      color: white;
      cursor: pointer;
    }
    
    button:disabled {
      background-color: #cccccc;
    }

Step 5: Run the Application

Run the following command to start the development server:

ng serve

Open your browser and navigate to http://localhost:4200/. You should see your form with the name, email, and age fields, along with validation.

Explanation

  • ReactiveFormsModule: This module provides the necessary tools to build reactive forms.
  • FormBuilder: This service simplifies form control creation and management.
  • FormGroup and FormControl: FormGroup is used to group form controls, while FormControl represents each input element.
  • Validators: Angular provides built-in validators like Validators.required and Validators.email for common validation tasks.

By following these steps, you’ve created a robust form using Angular’s reactive forms, ensuring efficient form handling and validation.