0

I am trying to understand the intricasies of implementing custom Angular controls for forms. Implementation of CustomValueAccessor should register callback for the change in state in "touched" by means of implementing registerOnTouched calllback. It's pretty clear that "touched" should be set when user interacts with the control. However, I am wondering when the state of touched should be reset to "false".

  registerOnTouched(onTouched: any) {
    this.onTouched = onTouched;
  }

  markAsTouched() {
    if (!this.touched) {
      this.onTouched();
      this.touched = true; // When would I set "touched to false?
  }
ben92
  • 80
  • 8

1 Answers1

0

I would suggest you to get the formGroup that you want and mark it as touched instead of implementing this custom behavior to the control.

this.form.markAsTouched();

You can see this answer as an example.

StPaulis
  • 2,844
  • 1
  • 14
  • 24
  • Thank you, this is helpful in cases when control is a wrapper around a formGroup. – ben92 Jan 10 '22 at 14:45
  • Not only in these cases. You can use `control.markAsTouched();` to update your form control directly. What I was trying to suggest is the you should remove this functionality out of the control. – StPaulis Jan 10 '22 at 15:14
  • Removing this functionality would constitute a violation of encapsulation principle. Form itself may not have understanding how control determines that it was touched. For example, imagine a numeric up/down spinner control. It is touched if user presses a button. Marking as touched therefore is control specific logic. – ben92 Jan 10 '22 at 15:54
  • 1
    Maybe "touched" variable should not be used at all. Maybe I should fire this.onTouched() unconditionally every time user interacts with the control? – ben92 Jan 10 '22 at 17:12
  • @ben92, yes, each time the user interacts you fire this.onTouched(). If you want to know if the FormControl is touched you need ask about the "ngControl".touched. -you can inject in constructor the ngControl it's a bit old, but take a look this [SO](https://stackoverflow.com/questions/57186593/how-to-pass-ngcontrol-status-to-child-component-in-angular-implementing-control/57189059#57189059) For untouch, you always make outside the control. It's equal a simple input, the FormControl is touched each time change, to mark as untouched you need make outside the control – Eliseo Jan 10 '22 at 21:42
  • Elisio, I have a problem understanding "you always make outside the control". "To make" most closely resembles "to create" or "to force" something. – ben92 Jan 14 '22 at 16:22
  • @ben92 Usually we have a container or parent component that we control the logic of the form and several form control components (children) that are responsible to bind the form control with the angular world. If you wanna do something whenever the form control is touched or not, is usually responsibility of the parent. – StPaulis Jan 16 '22 at 20:52