Skip programmatic changes in valueChanges of Angular 2 control

守給你的承諾、 提交于 2019-12-10 17:12:03

问题


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.


回答1:


You can use

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

See also

  • https://angular.io/docs/ts/latest/api/forms/index/AbstractControl-class.html#!#setValue-anchor
  • https://github.com/angular/angular/blob/e9f307f9488e44879dc027e5f4436fb6bc046fa4/modules/%40angular/forms/src/model.ts#L669



回答2:


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.



来源:https://stackoverflow.com/questions/41954810/skip-programmatic-changes-in-valuechanges-of-angular-2-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!