I'm building a search box in my Angular 2 app, trying to submit the value upon hitting 'Enter' (the form does not include a button).
Template
<input type="text" id="search" class="form-control search-input" name="search" placeholder="Search..." [(ngModel)]="query" (ngSubmit)="this.onSubmit(query)">
With a simple onSubmit function for testing purposes...
export class HeaderComponent implements OnInit { constructor() {} onSubmit(value: string): void { alert('Submitted value: ' + value); } }
ngSubmit doesn't seem to work in this case. So what is the 'Angular 2 way' to solve this? (Preferably without hacks like hidden buttons)
To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value. Explanation: We use the jQuery event. which to check the keycode on the keypress.
You can use Angular event bindings to respond to any DOM event. Many DOM events are triggered by user input. Binding to these events provides a way to get input from the user. To bind to a DOM event, surround the DOM event name in parentheses and assign a quoted template statement to it.
We can use angular keydown event to use Enter key as our submit key. Add keydown directive inside the form tag. Create a function to submit the form as soon as Enter is pressed. Assign the keydown event to the function.
Binding to user input events You can use Angular event bindings to respond to any DOM event. Many DOM events are triggered by user input. Binding to these events provides a way to get input from the user. To bind to a DOM event, surround the DOM event name in parentheses and assign a quoted template statement to it.
(keyup.enter)="methodInsideYourComponent()"
add this inside your input tag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With