45. Reactive Forms (RF) Setup and FormControl
Reactive Forms provide a model-driven approach where the form structure and validation are defined explicitly in the component class, offering greater control, scalability, and testability.
1. Import ReactiveFormsModule
Ensure this module is imported in your AppModule or feature module.
2. Using FormControl
FormControl is the fundamental building block of Reactive Forms. It represents a single input field and its state (value, validity).
Instantiating Controls
We typically instantiate controls in the component's constructor or ngOnInit.
typescript import { FormControl } from '@angular/forms';
export class ReactiveSetupComponent implements OnInit { // 1. Declare the FormControl instance usernameControl: FormControl | null = null;
ngOnInit(): void { // 2. Instantiate the control: initial value, validators array this.usernameControl = new FormControl('Default Name', Validators.required); } }
3. Linking Control to the Template
We link the component's FormControl instance to the HTML input using the [formControl] property binding.
html
<input type="text" [formControl]="usernameControl" id="username">
Is Valid: {{ usernameControl.valid }}
Reactive Changes (Observables)
Since Reactive Forms are model-driven, we can subscribe to changes on the control, treating the form data as a continuous stream (an Observable).
typescript ngOnInit(): void { // ... instantiation this.usernameControl.valueChanges.subscribe(newValue => { console.log('Username changed to:', newValue); }); }