Shareef
Shareef

Reputation: 361

Prevent (ngSubmit) when (keyup.enter) on an input is triggered in Angular 4

Here I have a form with many inputs. one of which is not part of the form builder. I am using it to create some custom data.

So the problem is I have added a (keyup.ente) event on this input element but it triggers the (ngSubmit) on the form.

I tried adding event.stopPropagation on (keyup.enter) but it is not working some reason.

Upvotes: 5

Views: 7254

Answers (2)

tony19
tony19

Reputation: 138216

The problem is the <form> is handling the keydown event before the <input> does, so you should use keydown.enter on your <input> instead. In addition, you should use event.preventDefault() to stop the event from reaching the <form> (and triggering the submit-event).

app.component.html

<form (ngSubmit)="onSubmit">
  ...
  <input (keydown.enter)="handleKeyEnter($event)">
</form>

app.component.ts

handleKeyEnter(event) {
  event.preventDefault();
  ...
}

demo

Upvotes: 6

ProllyGeek
ProllyGeek

Reputation: 15836

You can try this

app.component.html

<form [formGroup]="form" (ngSubmit)="onSubmit($event)" (keydown)="handleKeyupEnter($event)">
  <input type="text" [formControl]="form.controls['name']" placeholder="Name">
<br><br>
  <input type="text" placeholder="data" #entry >

  <br><br>
  <button type="submit">Submit</button>
</form>

app.component.ts

import { Component, ViewChild, ElementRef } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) { }

  @ViewChild('entry') entry: ElementRef;

  ngOnInit() {
    this.form = this.fb.group({
      name: ''
    })
  }

  onSubmit(e) {
    alert('Form Submitted');
    console.log(e);
  }

  handleKeyupEnter(event, value) {
    console.log(event)
    if(event.code=="Enter")
    event.preventDefault();

  }
}

if you need to exclude specific children from this behaviour (like your data input) , then do a check for event.target & event.srcElement

Upvotes: 2

Related Questions