Search code examples
angulareventskeypress

Angular 2: Pressing the enter key triggers a method and I don't know how to stop it


I've written a form, bound to an angular 2 component. When I press the enter-key in any text-input it starts a method bound to a (click) event event of a button.

This is the textfield where i press the enter-key:

<input type="text" class="form-control" name="name" [ngModel]="tutorial.name" #name="ngModel" required>

This is the button-click-method which gets triggered:

<button class="btn btn-success button-right" (click)="addEasy('')">+</button>

The button calls the 'addEasy()' method. This method pushes a new empty element to an array. The array is bound to an *ngfor. So whenever I press the enter button inside the first text-input-field i get another empty row inside my *ngFor.

I really have no idea how to solve this problem. Thanks for your help!


Solution

  • To prevent the form from submitting on enter, add the following in your <form> tag:

    <form (keydown.enter)="$event.preventDefault()"