When setting up a RxJS Subject
observable and subscribing directly, it's important to note that unless a value is pushed into it, nothing will be emitted. Therefore, using an external observable in this scenario may not be necessary.
An alternative approach would involve utilizing the valueChanges
observable of the FormControl
. By leveraging the valueChanges
, there is no need for binding to the change
event as well since any change in the element's value will trigger emission due to its association with a FormControl
.
To implement this method:
Control
ngOnInit() {
...
this.controls.controlName.valueChanges.pipe( // <-- form control here
debounceTime(300)
)
.subscribe(() => {
this.formValue.emit(this.dynamicForm.value);
});
}
Template
<input
required
[formControlName]="controls.controlName"
matInput
/>
Update: merging multiple observables
In cases where there are multiple controls involved, one effective approach is combining all the valueChanges
observables using RxJS merge
function.
ngOnInit() {
...
merge(
this.controls.controlName.valueChanges,
this.controls.controlPhone.valueChanges,
this.controls.controlId.valueChanges,
...
).pipe(
debounceTime(300)
)
.subscribe(() => {
this.formValue.emit(this.dynamicForm.value);
});
}