6

I'm subscribing to the valueChanges observable of an Angular 2 (2.2.1) control. It's defined in AbstractControl in @angular\forms\src\model.d.ts and it's doc string states that it will yiald changes from the UI as well as programmatic ones:

/**
 * Emits an event every time the value of the control changes, in
 * the UI or programmatically.
 */
valueChanges: Observable<any>;

How can I filter this down to give me only the changes from the UI and not the programmatic ones?

I think that the boolean props (pristine, dirty, touched, etc.) won't help me, because even after a control is marked dirty - indicating a change from the UI, which I would like to capture - there might be further programmatic changes, which I would like to ignore.

EagleBeak
  • 6,939
  • 8
  • 31
  • 47

2 Answers2

18

You can use

control.setValue(123, {emitEvent: false})

See also

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    Frankly, its a hack. Wait until you forget that `valueChanges` latest value can get out of sync with `control.value`, or someone on the team has not been told about this black magic. – rgripper Apr 26 '17 at 04:23
  • 1
    @rgripper Sure, suppressing the notification is a hack, but that's what the question was about. Perhaps the control should provide two different `valueChanges` streams (all and by user-actions), but that could be difficult, because different pieces work together and the mechanism also supports custom form controls and therefore would also require them to provide such events differently. Perhaps worth a bug report (if none exists yet). – Günter Zöchbauer Apr 26 '17 at 06:33
0

Well, you want to ignore changes made by programatically, that means changes made by you (the programmer, not the end user).

When you make a programatic change, you may set a property in a shared service. When you subscribe the valueChanges observable, simply consult the shared service every time.

coder
  • 301
  • 1
  • 7
  • 12