Forms
What it means
Section titled βWhat it meansβAngular offers two form-building approaches. Template-driven forms use directives like ngModel directly in the template, with less TypeScript code β good for simple forms. Reactive forms define the formβs structure and validation in the component class using FormGroup/FormControl β more explicit, more testable, and generally preferred for anything non-trivial.
Examples
Section titled βExamplesβ// Template-driven (requires FormsModule)@Component({ selector: 'app-login', template: ` <form #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm.value)"> <input name="email" [(ngModel)]="email" required email> <button [disabled]="loginForm.invalid">Log in</button> </form> `,})export class LoginComponent { email = ''; onSubmit(value: any) { console.log(value); }}
// Reactive (requires ReactiveFormsModule)import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({ selector: 'app-login', template: ` <form [formGroup]="form" (ngSubmit)="onSubmit()"> <input formControlName="email"> <button [disabled]="form.invalid">Log in</button> </form> `,})export class LoginComponent { form = new FormGroup({ email: new FormControl('', [Validators.required, Validators.email]), }); onSubmit() { console.log(this.form.value); }}Common mistake
Section titled βCommon mistakeβReading the form value directly from an <input> via ngModel or the DOM instead of through the FormGroup/FormControl API β this bypasses Angularβs built-in validation state (.valid, .dirty, .errors) that reactive forms track for you.
// Reading raw DOM value -- loses all of Angular's validation trackingonSubmit() { const email = (document.getElementById('email') as HTMLInputElement).value;}
// Correct -- use the form's own value, with validation state already trackedonSubmit() { if (this.form.valid) { console.log(this.form.value.email); }}Quick practice
Section titled βQuick practiceβ-
Whatβs the main difference between template-driven and reactive forms?
Answer
Template-driven forms define structure and validation mostly in the HTML template via directives; reactive forms define it explicitly in the component class usingFormGroup/FormControl, which is more testable and scales better to complex forms. -
What module must you import to use reactive forms?
Answer
ReactiveFormsModule(or the standalone-component equivalent import) β template-driven forms instead requireFormsModule. -
What information does
form.validgive you that reading the raw DOM input value doesnβt?Answer
Whether all the form's validators currently pass β reading the DOM value directly gives you the raw text but none of Angular's tracked validation state.