Reactive Forms
Reactive forms in Angular are built programmatically in the component class using FormBuilder, FormGroup, and FormControl.
They offer more power and flexibility, making them ideal for complex forms and advanced validation.
They offer more power and flexibility, making them ideal for complex forms and advanced validation.
Example: Build a simple registration form
Step 1: Create a new Angular project
ng new angular-forms
Step 2: Generate a form component
ng g c form-component
Step 3: Create the form in HTML
In 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="email">Email:</label> <input type="email" id="email" formControlName="email" /> </div> <pre></pre> <div class="form-group"> <label for="password">Password:</label> <input type="password" id="password" formControlName="password" /> </div> <pre></pre> <button type="submit" [disabled]="userForm.invalid">Submit</button> </form></div>
Step 4: Add form logic in TypeScript
In form-component.component.ts
import { Component } 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 some basic styling
In form-component.component.css
div { text-align: center;}
label { text-align: left;}
button:disabled { background-color: #ccc; cursor: not-allowed;}
Step 6: Display the form in the app
In app.component.html
<app-form-component></app-form-component>
And in app.module.ts, import ReactiveFormsModule
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({ imports: [ BrowserModule, ReactiveFormsModule ], // other code...})export class AppModule { }
Step 7: Run the application
ng serve
Visit http://localhost:4200 - and try filling the form.
Key Point
- Reactive forms use TypeScript to create and manage form controls.
- Great for dynamic forms and complex validation.
- Always import ReactiveFormsModule to use reactive forms.