How to observe touched event on Angular 2 NgForm?

后端 未结 4 1852
青春惊慌失措
青春惊慌失措 2020-12-18 18:53

It is possible to subscribe a callback to an NgForm\'s valueChanges observable property in order to react to changes in the values of the controls

4条回答
  •  感情败类
    2020-12-18 19:30

    If your issue was anything like mine, I was trying to mark a field as touched in one component and then respond to that in another component. I had access to the AbstractControl for that field. The way I got around it was

    field.markAsTouched();
    (field.valueChanges as EventEmitter).emit(field.value);
    

    And then I just subscribed to valueChanges in my other component. Noteworthy: field.valueChanges is exported as an Observable, but at runtime it's an EventEmitter, making this a less than beautiful solution. The other limitation of this would obviously be the fact that you're subscribing to a lot more than just the touched state.

提交回复
热议问题