Loading

Reactive Forms

  • Reactive forms, on the other hand, are created programmatically in the component class. They offer more flexibility and are well-suited for complex forms with intricate validation needs

Example:

Step 1: Create an Angular project using Angular CLI.

ng new angular-forms

Step 2: Create a new component message

ng g c form-component

Step 3: Now create the form in the ‘form-component.component.html’.

<div class="container">
  <h2>Reactive Form Example</h2>
  <form [formGroup]="userForm" (ngSubmit)="submit()">
    <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" id="name" formControlName="name" />
    </div>
    <pre></pre>
    <div class="form-group">
      <label for="name">Email:</label>
      <input type="email" id="email" formControlName="email" />
    </div>
    <pre></pre>
    <div class="form-group">
      <label for="name">Password:</label>
      <input type="password" id="password" formControlName="password" />
    </div>
    <pre></pre>
    <button type="submit" [disabled]="userForm.invalid">Submit</button>
  </form>
</div>

Step 4: Edit the 'form-component.component.ts' to define the function and attributes.

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

@Component({
  selector: 'app-form-component',
  templateUrl: './form-component.component.html',
  styleUrls: ['./form-component.component.css']
})
export class FormComponentComponent {

  userForm: FormGroup
  constructor(private fb: FormBuilder) {
    this.userForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(6)]]
    });
  }
  submit() {
    if (this.userForm.valid) {
      console.log('Form Submitted', this.userForm.value);
    }
  }
}

Step 5: Add CSS to ‘form-component.component.css’ for better styling.

div {
    text-align: center;
}

label {
    text-align: left;
}

button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}

Step 6: Add the ‘<app-form-component></app-form-component>’ to the ‘app.component.html’ to include the ‘Form-Component’ in the main application. Also, add the ReactiveFormsModule in ‘app.module.ts’.

<app-form-component></app-form-component>

Step 7: Now run or compile the application.

ng serve

You will see the result on http://localhost:4200