Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Angular FAQ: Top Questions

10. How do forms work in Angular?

Angular provides robust support for building forms through two main approaches: Template-Driven Forms and Reactive Forms. Both approaches allow developers to collect, manage, and validate user input efficiently using built-in directives, data binding, and form control mechanisms.

Choosing between template-driven and reactive forms depends on your application's complexity, maintainability requirements, and preference for declarative or programmatic control.

  • Template-Driven Forms:
    • Forms are defined directly in the HTML using directives like ngModel, required, and ngForm.
    • Best suited for simple forms with basic validation.
    • Relies heavily on Angular’s data binding and automatic form tracking.
    • Requires importing FormsModule.
  • Reactive Forms:
    • Forms are defined programmatically in the component class using FormControl, FormGroup, and FormBuilder.
    • Offers full control over form state, validation, and dynamic form creation.
    • Ideal for complex scenarios, including dynamic or conditionally-rendered fields.
    • Requires importing ReactiveFormsModule.
  • Validation:
    • Both form types support built-in validators (e.g., required, minlength) and custom validators.
    • Angular tracks validation state using valid, touched, dirty, and errors properties.

// Template-Driven Form (HTML)

<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)">
  <input name="username" [(ngModel)]="username" required />
  <button type="submit" [disabled]="!userForm.valid">Submit</button>
</form>
        

// Reactive Form (TS + HTML)

// app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  userForm = new FormGroup({
    username: new FormControl('', [Validators.required, Validators.minLength(3)])
  });

  onSubmit() {
    console.log(this.userForm.value);
  }
}
        

// app.component.html
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
  <input formControlName="username" />
  <button type="submit" [disabled]="!userForm.valid">Submit</button>
</form>
        

Explanation of the Example Code:

  • In the template-driven example, the form uses [(ngModel)] and Angular automatically tracks form state via ngForm.
  • In the reactive example, the form is defined as a FormGroup in the TypeScript file and bound to the HTML with formGroup and formControlName directives.
  • Both examples include a submit handler and simple validation logic using required and Validators.

Angular forms provide powerful capabilities for capturing, validating, and reacting to user input in dynamic and scalable ways, whether you prefer a declarative or programmatic approach.