import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, ReactiveFormsModule],
styles: [`
form { display: grid; gap: 10px; max-width: 360px; }
label { display: grid; gap: 6px; }
small { color: crimson; }
`],
template: `
<h3>Reactive Forms</h3>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<label>
Name
<input formControlName="name" placeholder="Your name" />
<small *ngIf="form.controls.name.invalid && (form.controls.name.dirty || form.controls.name.touched || submitted)">
<span *ngIf="form.controls.name.errors?.['required']">Name is required.</span>
<span *ngIf="form.controls.name.errors?.['minlength']">Min 3 characters.</span>
</small>
</label>
<label>
Email
<input formControlName="email" placeholder="you@example.com" />
<small *ngIf="form.controls.email.invalid && (form.controls.email.dirty || form.controls.email.touched || submitted)">
<span *ngIf="form.controls.email.errors?.['required']">Email is required.</span>
<span *ngIf="form.controls.email.errors?.['email']">Email must be valid.</span>
</small>
</label>
<label style="align-items:center; grid-auto-flow: column; justify-content: start;">
<input type="checkbox" formControlName="newsletter" />
Subscribe to newsletter
</label>
<button type="submit" [disabled]="form.invalid">Submit</button>
</form>
<p>Status: {{ form.status }}</p>
<p>Value: {{ form.value | json }}</p>
<p *ngIf="submitted" style="color: seagreen;">Submitted!</p>
`
})
export class App {
fb = new FormBuilder();
submitted = false;
form = this.fb.group({
name: ['', [Validators.required, Validators.minLength(3)]],
email: ['', [Validators.required, Validators.email]],
newsletter: [false],
});
onSubmit() {
this.submitted = true;
}
}
bootstrapApplication(App);
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Angular Reactive Forms</title>
</head>
<body>
<app-root></app-root>
</body>
</html>