I have a form with one field that acts as autocomplete. If the user enters a word and presses enter, the content of the field should be added to a list below the field.
Prevent a form from submittion on enter or by clicking a button
<textarea (keydown.enter)="provoked($event)"></textarea>
<button (keydown.enter)="provoked($event)" (click)="provoked($event)"></button>
provoked($event) {
$event.preventDefault()
}
in case if you need to pass data to the method, then try
<textarea (keydown.enter)="provoked($event, data)"></textarea>
<button (keydown.enter)="provoked($event, data)" (click)="provoked($event, data)"></button>
provoked($event, data) {
$event.preventDefault()
// process the data here
}
So the answer was actually quite simple... It wasn't Event.preventDefault()
since I was listening for Enter on the input field and not the button. Removing type="submit"
from the button
wasn't enough since all buttons are type submit by default. The only change necessary was on the button element, adding type="button"
explicitly and adding a (click)
listener:
<button type="button" (click)="onSubmit()" class="btn btn-primary pull-right" [disabled]="!profileForm.valid">Save</button>
The only kind-of problem: Now submitting the form with enter never works. Would be a tiny bit more elegant to only prevent enter from submitting the form when the focus is in the autocomplete input field.
Edit:
To only prevent enter from submitting the form when the cursor is in the autocomplete field can be achieved by using Ankit Singh's solution and modifying it a bit:
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()" method="post" (keydown.enter)="$event.target.id != 'skill_string'" *ngIf="!showSuccessMessage">
(Note: The condition has to return false to prevent the default action to be triggered)
Of course we then need our regular submit button again (without the click event attached, or the form will submit twice):
<button type="submit" class="btn btn-primary pull-right" [disabled]="!profileForm.valid">Save</button>
You could also check the event.target.classList
if you want to use a .autocomplete
class. Or move the checking logic to a function into which you pass the $event
.
Events in Angular 2 behave like normal DOM events. To capture the event object, pass $event
as a parameter in the event callback from the template:
Html:
<button (keyup.enter)="skillsHandleEnter($event, skillString)"></button>
JavaScript using Event.preventDefault():
@Component(...)
class MyComponent {
skillsHandleEnter(event, skillString) {
event.preventDefault();
// ... your logic
}
}
Try
<form (keydown.enter)="$event.target.tagName == 'TEXTAREA'" [formGroup]="profileForm" (ngSubmit)="onSubmit($event)">
It will also allow enter
in Textarea
s.