KDC
KDC

Reputation: 1471

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

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)

Upvotes: 36

Views: 32433

Answers (4)

Naveen Motwani - AIS
Naveen Motwani - AIS

Reputation: 619

You can put this text box inside a form tag and set ngSubmit event on form i.e.

<form (ngSubmit)="YouMethod()">
    <input type="text" class="form-control input-lg" />
</form>

Upvotes: 3

KDC
KDC

Reputation: 1471

For the sake of completeness, this solution worked for me as well:

<form (keydown)="keyDownFunction($event)"><input type="text" /></form>

Upvotes: 0

Dimitri Lavren&#252;k
Dimitri Lavren&#252;k

Reputation: 4879

In normal HTML you need a <button type="submit" ></button> or <input type="submit" /> to submit the form when pressing enter. These elements can be hidden by css but must be present inside the form. ng-submit should be bound to the normal onsubmit event and it has the same conditions to be triggered.

Also from the code you have posted, you have no form element but only the input field, and the ng-submit directive only works with forms because input elements have no onsubmit JS event.

Upvotes: 1

Godfather
Godfather

Reputation: 5891

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

Upvotes: 102

Related Questions