Reactive Forms Data Flow
Demonstrates the data flow in reactive forms by using form control objects that emit changes asynchronously, keeping in line with Angular's unidirectional data flow concept.
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.component.html',
styleUrls: ['./reactive-form.component.css']
})
export class ReactiveFormComponent implements OnInit {
// Define a FormGroup instance
form: FormGroup;
ngOnInit(): void {
// Initialize FormGroup with form controls
this.form = new FormGroup({
// Define a form control with an initial value
name: new FormControl(''),
email: new FormControl('')
});
// Subscribe to value changes in the entire form
this.form.valueChanges.subscribe(values => {
console.log('Form value changes:', values);
});
// Subscribe to value changes in a single form control
this.form.get('name').valueChanges.subscribe(value => {
console.log('Name value changes:', value);
});
}
// Function to handle form submission
onSubmit(): void {
console.log('Form Submitted!', this.form.value);
}
}
This Angular component sets up a reactive form with two form controls for 'name' and 'email'. It initializes the form, subscribes to value changes on the entire form as well as on the individual 'name' form control, and handles form submissions.