Web Develop Wolf
Web Develop Wolf

Reputation: 6346

How to fire a function using the Enter Key in Angular 9

I have a button with a (click) event that currently fires a method in an Angular component which works perfectly, but I also need to fire the same method if the user hits the enter key from the input box so the user has a choice.

Here' the HTML I'm using for the input and the button:

<div class="input-group input-group-sm mt-3">
    <input autocomplete="off" list="autocompleteOff" type="text" class="form-control" placeholder="E.G. 'What is a beneficary?'" aria-label="Ask" [(ngModel)]="userQuestion" id="userQuestion" name="userQuestion" [ngStyle]="{'background-color': brand?.colours.secondary, 'color': brand?.colours.primary}">
    <div class="input-group-append">
      <button id="user-btn" class="btn btn-secondary" type="button" (click)="askQuestion()" [ngStyle]="{'background-color': brand?.colours.primary, 'color': brand?.colours.secondary}">Ask</button>
    </div>
  </div>

Can I do this form the HTML side or do I need to set up a listener for the enter key?

Upvotes: 3

Views: 1590

Answers (3)

prakriti vishwakarma
prakriti vishwakarma

Reputation: 11

This is already answered in Fire a method when click an Enter key <input ng-keyup="$event.keyCode == 13 ? MyFunc() : null" >

Upvotes: 1

0x1211
0x1211

Reputation: 225

You may edit your button element type attribute to type="submit".

Upvotes: 1

G&#233;r&#244;me Grignon
G&#233;r&#244;me Grignon

Reputation: 4238

You can use keyup.enter :

<input (keyup.enter)="askQuestion()"/>

Upvotes: 7

Related Questions