MyInternships.in

Forms & Validation

Angular Reactive Forms

Reactive forms define the model in the component class. A FormGroup holds named FormControls, the template binds to it with formGroup and formControlName, and validation rules are plain functions.


What is Reactive Forms in Angular?

Reactive forms define the model in the component class. A FormGroup holds named FormControls, the template binds to it with formGroup and formControlName, and validation rules are plain functions.

Reactive Forms example

Building the model with FormBuilder
TypeScript
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';

@Component({ standalone: true, imports: [ReactiveFormsModule], templateUrl: './apply.html' })
export class ApplyComponent {
  private fb = inject(FormBuilder);

  form = this.fb.group({
    name:  ['', [Validators.required, Validators.minLength(2)]],
    email: ['', [Validators.required, Validators.email]],
    phone: ['', [Validators.required, Validators.pattern(/^[6-9]\d{9}$/)]],
    agree: [false, Validators.requiredTrue],
  });

  submit(): void {
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    this.api.apply(this.form.getRawValue()).subscribe();
  }
}

Binding the template

HTML
<form [formGroup]="form" (ngSubmit)="submit()">
  <input formControlName="name">
  @if (form.controls.name.touched && form.controls.name.errors?.['required']) {
    <small>Name is required</small>
  }
  <button [disabled]="form.invalid">Submit</button>
</form>

Key points to remember

  • Import ReactiveFormsModule, not FormsModule.
  • markAllAsTouched() on an invalid submit reveals every error at once.
  • valueChanges is an Observable of the form value — useful for autosave and dependent fields.
  • getRawValue() includes disabled controls; value does not.

Common mistakes with Reactive Forms

  • Importing FormsModule by mistake and getting "formGroup is not a known property of form".
  • Using setValue when you mean patchValue — setValue requires every control to be present.
  • Subscribing to valueChanges without unsubscribing.

Angular Reactive Forms— Interview Questions & FAQs

What is the difference between setValue and patchValue?+

setValue requires a value for every control in the group and throws if one is missing. patchValue updates only the keys you supply, which is what you usually want when prefilling part of a form.

Related Angular Topics

Keep learning with these closely related lessons.

Ready to use your Angular skills?

Find verified Angular internships and fresher developer jobs across India.

Browse Angular Internships