Unified Control State Change Events in Angular
One of the standout features introduced in version v18.0.0 of Angular is the addition of a powerful new property called events
on AbstractControl
. This property exposes an observable that tracks changes in value, pristine state, touch status, and the control status:
export class AppComponent {
ngOnInit() {
// Remember to unsubscribe to avoid memory leaks
new FormControl('').events.subscribe(e => {
if(e instanceof StatusEvent) {
console.log(e.status)
}
})
}
}
The events
observable emits four distinct types of events: PristineEvent
, StatusEvent
, TouchedEvent
, and ValueChangeEvent
. Each event is an extension of ControlEvent
, providing essential contextual information through its source
property, which indicates the control
that emitted the event. Let's delve into the specifics of each event:
class PristineEvent extends ControlEvent {
readonly pristine: boolean;
}
class StatusEvent extends ControlEvent {
readonly status: FormControlStatus;
}
class TouchedEvent extends ControlEvent {
readonly touched: boolean;
}
class ValueChangeEvent<T> extends ControlEvent<T> {
readonly value: T;
}
- PristineEvent: Indicates whether the control has been interacted with (
pristine
property). - StatusEvent: Provides the current status of the form control (
status
property). - TouchedEvent: Signals whether the control has been touched (
touched
property). - ValueChangeEvent: Delivers the updated value of the control (
value
property)
Follow me on Medium or Twitter to read more about Angular and JS!