angulartypescriptangular2-forms

How to observe touched event on Angular 2 NgForm?


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 of the form.

I need, in the same fashion, to react to the event of the user touching one of the form controls.

This class seem to define the valueChanges Observable and the touched property is defined as a boolean.

Is there a way to to react to the "control touched" event?


Solution

  • Anyone looking for this solution now there's way easier way that doesn't require any modifications to formControl itself. We can now subscribe to events on formControl. The events observable includes TouchedChangeEvent (as well as ValueChangeEvent, StatusChangeEvent, PristineChangeEvent, etc...)

        this.formControl.events.subscribe((event: ControlEvent<T>) => {
            if (e instanceof TouchedChangeEvent){
                if (e.touched){
                    // Do stuff
                } else {
                    // Do other stuff...
                } 
            }
          
        });
    

    From the docs, events is:

    A multicasting observable that emits an event every time the state of the control changes. It emits for value, status, pristine or touched changes

    See a StackBlitz code example here. The example triggers TouchedChangeEvent event by calling markAsTouched(), and then calling markAsUntouched().