Skip to content

Forms

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.

// 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); }
}

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 tracking
onSubmit() {
const email = (document.getElementById('email') as HTMLInputElement).value;
}
// Correct -- use the form's own value, with validation state already tracked
onSubmit() {
if (this.form.valid) {
console.log(this.form.value.email);
}
}
  1. What’s the main difference between template-driven and reactive forms?

    AnswerTemplate-driven forms define structure and validation mostly in the HTML template via directives; reactive forms define it explicitly in the component class using FormGroup/FormControl, which is more testable and scales better to complex forms.
  2. What module must you import to use reactive forms?

    AnswerReactiveFormsModule (or the standalone-component equivalent import) β€” template-driven forms instead require FormsModule.
  3. What information does form.valid give you that reading the raw DOM input value doesn’t?

    AnswerWhether 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.