1

Here is simple input box in a reactive form: Html:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <input type="text" formControlName="box" (keyup.enter)="dosomething()">
  <button>Submit</button>
</form>

TS:

  dosomething() {
    this.cd.detectChanges(); // private *cd*: ChangeDetectorRef
    console.log(this.form.untouched);
  } 
  onSubmit() {
    console.log('from submit: ', this.form.untouched);
  }

input something in the input box

-> click enter, I got: true;

-> click the submit button, I got: false

In this case, cz the input box has already been touched, so, we should expect the false.

How can I get the false when clicking enter in the input box?

enter link description here

Yue Dong
  • 85
  • 5
  • this.form.markAllAsTouched() should do the trick – Gerardo Gonzalez Dec 06 '22 at 23:49
  • @GerardoGonzalez Thanks, it's worded, but seems we manually change the form statues as touched. Don't know if it's the only solution for it~ – Yue Dong Dec 08 '22 at 06:12
  • form.untouched is updated when the focus moves on to next element. So when you press enter key the focus is still on the input element so form does not update the untouched value so it stays **true** when you click enter button and when you press the submit button the focus moves on to the submit button so form fields gets updated and untouched value becomes **false**. – Shailesh B Dec 12 '22 at 04:55

0 Answers0