Angular
Reactive Forms
Build a typed reactive form with FormBuilder and validators.
By EZ4Code Team
formsreactive-forms
Code
import { Component, inject } from "@angular/core";
import { FormBuilder, ReactiveFormsModule, Validators } from "@angular/forms";
@Component({
selector: "app-login",
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<input formControlName="email" placeholder="Email" />
<input formControlName="password" type="password" />
<button [disabled]="form.invalid">Login</button>
</form>
`
})
export class LoginComponent {
private fb = inject(FormBuilder);
form = this.fb.group({
email: ["", [Validators.required, Validators.email]],
password: ["", [Validators.required, Validators.minLength(6)]]
});
submit() {
if (this.form.valid) console.log(this.form.value);
}
}Explanation
Reactive forms model form state as an immutable FormGroup of FormControls. FormBuilder reduces boilerplate, and Validators attach sync rules. The [formGroup] binding connects the model to the template, exposing validity and value streams.
More Angular Snippets
Component Basics
Define an Angular component with selector, template, and styles.
Template Syntax & Binding
Interpolation, property, event, and two-way binding in Angular templates.
Built-in Directives
Use *ngIf, *ngFor, ngClass, and ngStyle to shape the DOM.
Pipes & Custom Pipe
Transform template values with built-in and custom pipes.
Services & Dependency Injection
Create an injectable service and consume it in a component.
Routing Configuration
Define routes with params, lazy loading, and redirects.