Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular 2, how do I submit an input type="text" value upon pressing enter?

Tags:

angular

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)

like image 680
KDC Avatar asked Jul 29 '16 12:07

KDC


People also ask

How do you submit a form when Enter key is pressed?

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.

How to bind input value in Angular?

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.

How do you make Enter button on Form submit in angular?

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.

How to take user input in Angular?

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.


1 Answers

(keyup.enter)="methodInsideYourComponent()" add this inside your input tag

like image 169
Godfather Avatar answered Sep 20 '22 21:09

Godfather