0
votes

I have a form with 'updateOn: 'submit' since we only need to validate once our user submits. This has, however, caused the submit on enter to stop working: it triggers the validation, but acts as if the form had no values in it and only shows the Validators.required message. When i printed the form into console it also sees the form as empty. When the submit is invoked by clicking on the submit button, everything works well.

Is there a way to either detect the pressing of enter key and programmatically invoke the native submit to trigger validation, or tackle this problem in any smarter way?

I have reproduced it on this Stackblitz link: https://stackblitz.com/edit/angular-p4p5k9?file=src%2Fapp%2Fapp.component.ts

How to simulate: 1. type a value into the textfield and hit Submit. The value is seen in the console 2. Type something else in the textfield and hit enter. The new value hasn't updated, the old value is seen in the console instead.

I need to somehow invoke the programmatic submit on enter so that when the submit() method is invoked in the enterHit subscription, the form already has the new values in it.

2
Patel Rushi's last comment is what fixed my problem. - thedoseoftea

2 Answers

0
votes

You can create a boolean variable hasSubmittedOnce and set its initial value to false and on form submit change its value to true

private hasSubmittedOnce: boolean = false;

onSubmit() {
 if(!this.hasSubmittedOnce) {
   this.hasSubmittedOnce = true;
 }
}

after that update your validation check, add hasSubmittedOnce condition, if hasSubmittedOnce is true then only validate values and show error messages

0
votes

in your ts file take one variable

isSubmitted:Boolean = false;

And give that to particular Validation condition.Example as below

  <div *ngIf="testForm.get('amount').errors && submitted" class="text-danger">
      <div *ngIf="testForm.get('amount').errors.required && submitted" class="fontSize12">Amount is
        required
      </div>
  </div>

And your button click should be

submitForm(form:FormGroup) {
    this.isSubmitted = true;
}