tb / ng2-nouislider

Angular2 noUiSlider directive
http://tb.github.io/ng2-nouislider/
MIT License
184 stars 114 forks source link

Value not updated when using the same control on another input #189

Closed gergelybodor closed 6 years ago

gergelybodor commented 6 years ago

I have the same form control attached to a simple input and a nouislider element. They both set the form control value separately, but they don't affect each other's value. How should I set up my form so that when I change the value in the input, the slider gets updated too with the new value (and the same for the other way)?

I created a stackblitz project for this.

Here is the code I use:

html:

<code>form disabled: {{ form.get('single').disabled }}</code>
<br>
<code>form value: {{ form.get('single').value }}</code>
<form [formGroup]="form">
  <input type="text" [formControl]="form.get('single')">
  <nouislider [min]="0" [max]="10" [step]="0.1 [formControl]="form.get('single')"></nouislider>
</form>

<div class="btn-group">
  <button type="button" class="btn btn-primary (click)="toggleDisabled()">
    {{form.get('single').disabled ? 'Enable': 'Disable'}}
  </button>
</div>

component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  form: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.form = this.formBuilder.group({ 'single': [3] });
    // this.watchFormChanges();
  }

  watchFormChanges() {
    this.form.get('single').valueChanges
      .pipe(debounceTime(300))
      .subscribe(v => {
        this.form.get('single').setValue(v, { onlySelf: true, emitEvent: false });
      });
  }

  toggleDisabled() {
    const control = this.form.get('single');
    control.enabled ? control.disable() : control.enable();
  }
}

Funny part is that disabling works on both, and if you use the commented out method call it works because we set the control value manually.

So my question is, am I doing something wrong here? What do I do so that my commented out code is not necessary?

There is an ongoing question on stackoverflow about this.

gergelybodor commented 6 years ago

Apparently you are not supposed to use the same form control on two different html elements, my bad. My workaround works though. The only downside is that the input will only update when you let go of the slider or when the debounce time runs out.