0

I have a simple angular form, for example:

  <form [formGroup]="form">
    <div>
      <input type="text" (keydown.enter)="onEnterPerssed($event)" [formControl]="myList" formControlName="myList">
    </div>
   <br>

    <p *ngIf="sendData" class="mt-1">Data send successfully</p>

    <button type="submit" (click)="onSubmit(form)" class="btn btn-block btn-primary mt-2" style="width: 100px;" [disabled]="form.invalid">
    Submit
    </button>
  </form>
export class AppComponent implements OnInit {
  sendData: boolean = false;

  form: FormGroup;
  isDisabled: boolean = true;
  myList: FormControl = new FormControl('sdfsdf', [Validators.required  ]);

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.form = this.fb.group({
      myList: this.myList
    });
  }

  onSubmit(form): void {
    this.sendData = true;
    console.log('data send successfully');
  }

  onEnterPerssed(event: Event) {
    event.stopPropagation();
    console.log('asdasfasfsfafasfasf');
  }
}

Is there any solutions on how to prevent submitting form while we click Enter on the input field, without changing button type (submit => button)

  • Does this answer your question? [Prevent users from submitting a form by hitting Enter](https://stackoverflow.com/questions/895171/prevent-users-from-submitting-a-form-by-hitting-enter) – GrafiCode Dec 20 '19 at 14:43
  • In the code example you provided, the Enter key disabled in the whole document. I try to understand why event.stopPropagation() doesn't work in the input filed. – Petia Biloshytsky Dec 20 '19 at 14:46
  • what do you mean `the Enter key disabled in the whole document`? you can actually use the enter key to fill a textarea, for instance. – GrafiCode Dec 20 '19 at 14:49

2 Answers2

1

Change submit event on form tag, and remove click event from submit button.

<form [formGroup]="form" (ngSubmit)="onSubmit($event)">
onSubmit(event) {
    event.preventDefault();
    // logic goes here
}

ngSubmit ensures that the form doesn’t submit when the handler code throws (which is the default behaviour of submit) and causes an actual http post request.

Plochie
  • 3,944
  • 1
  • 17
  • 33
0

Try this in the template:

Use (keydown.enter)="$event.preventDefault() inside the form tag

<form [formGroup]="form" (keydown.enter)="$event.preventDefault()">
    <div>
      <input type="text" (keydown.enter)="onEnterPerssed($event)" [formControl]="myList" formControlName="myList">
    </div>
   <br>

    <p *ngIf="sendData" class="mt-1">Data send successfully</p>

    <button type="submit" (click)="onSubmit(form)" class="btn btn-block btn-primary mt-2" style="width: 100px;" [disabled]="form.invalid">
    Submit
    </button>
  </form>
Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42