Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

angular

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?

like image 453
Web Develop Wolf Avatar asked Jan 19 '26 00:01

Web Develop Wolf


2 Answers

You can use keyup.enter :

<input (keyup.enter)="askQuestion()"/>
like image 178
Gérôme Grignon Avatar answered Jan 21 '26 17:01

Gérôme Grignon


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

like image 45
0x1211 Avatar answered Jan 21 '26 16:01

0x1211



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!