I have a simple Search Component which contains a Reactive Form with 2 elements:
So far I use myFormGroup.valueChanges.subscribe(...)
to execute my search method.
Now the problem is, that I want to debounce the text input. And at the same time not debounce the checkbox, so the search method is getting executed instantly when clicking the checkbox.
Using valueChanges.debounceTime(500)
will of course debounce the whole form. That's not what I want.
This is a stripped down example. The real form has some more inputs. Some should be debounced and some shouldn't.
Is there any easy way to get this done? Or do I have to subscribe to every form control separately?
Would be nice to see how you did solve this.
Thanks in advance.
export class SearchComponent {
myFormGroup: FormGroup;
constructor(fb: FormBuilder) {
this.myFormGroup = fb.group({
textInput: '',
checkbox: false
});
}
ngOnInit() {
this.myFormGroup.valueChanges.subscribe(val => {
// debounce only the textInput,
// and then execute search
});
}
}
Template Driven Forms are based only on template directives, while Reactive forms are defined programmatically at the level of the component class. Reactive Forms are a better default choice for new applications, as they are more powerful and easier to use.
The Reactive Forms Module in Angular allows you to add synchronous and asynchronous validators to form elements. Synchronous validators of a form element always run when a keyup event happens on that element.
In Angular, a reactive form is a FormGroup that is made up of FormControls. The FormBuilder is the class that is used to create both FormGroups and FormControls.
Create each individual FormControl before adding them to the form group and then you can control the valueChanges observable per FormControl
this.textInput.valueChanges
.pipe(
debounceTime(400),
distinctUntilChanged()
)
.subscribe(res=> {
console.log(`debounced text input value ${res}`);
});
the distinctUntilChanged will make sure only when the value is diffrent to emit something.
Debounce the text control's valueChanges
observable, then use combineLatest()
to combine it with the checkbox control's valueChanges
observable.
Simple example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With