Update form data while sliding mat slider if it's a form control of a reactive form

Viewed 2038

I have a slider that is a form control of a reactive form. I want the form data to update WHILE I'm sliding the slider.

Right now, the data gets updated when I release the slider.

I could probably solve my problem with this Get angular2 md-slider value while sliding but I feel like it's not the best answer because the form data will be updated twice. (on slide, and when the user release the slider) And also I feel like it defeats the purpose of having a reactive form if I have to manually update the data behind the scene.

2 Answers

Try this, it works for me. In html

<mat-slider thumbLabel class="slider" min="1" max="20" step="1" [formControl]="sliderControl"></mat-slider>

In ts

...
sliderControl = new FormControl(10);
...
ngOnInit(): void {
    ...
    this.sliderControl.valueChanges.subscribe(value => {
        console.log(value);
    });
}

To get it updating in real time (I'm using this to indicate the angle of a gradient where there's a preview) you may need to add

 (input)="sliderControl.setValue($event.value)"

Otherwise there's a slight delay.

Related