Core Concepts
Forms
Build and validate forms with Angular's powerful Reactive Forms and Template-Driven approaches.
Reactive Forms (Recommended)
Define form structure in TypeScript, providing full control and easier testing. Uses FormBuilder, FormGroup, and FormControl.
Template-Driven Forms
Define form structure in the template using directives. Simpler for basic forms.
Validation
Angular provides built-in validators (Validators.required, Validators.email, etc.) and supports custom validators.
Example
typescript
// signup.component.ts - Reactive Forms
import { Component } from '@angular/core';
import { FormBuilder, Validators, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
@Component({
standalone: true,
imports: [ReactiveFormsModule, CommonModule],
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div>
<input formControlName="email" placeholder="Email" />
<span *ngIf="form.get('email')?.errors?.['required'] && form.get('email')?.touched">
Email is required
</span>
<span *ngIf="form.get('email')?.errors?.['email']">
Invalid email format
</span>
</div>
<div>
<input formControlName="password" type="password" placeholder="Password" />
<span *ngIf="form.get('password')?.errors?.['minlength']">
Password must be at least 8 characters
</span>
</div>
<button type="submit" [disabled]="form.invalid || loading">
{{ loading ? 'Signing up...' : 'Sign Up' }}
</button>
</form>
`,
})
export class SignupComponent {
loading = false;
form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]],
});
constructor(private fb: FormBuilder) {}
onSubmit() {
if (this.form.valid) {
this.loading = true;
console.log(this.form.value);
}
}
}Try it yourself — TYPESCRIPT