3

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?

3 Answers 3

7

You can use keyup.enter :

<input (keyup.enter)="askQuestion()"/>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.