physicsboy
physicsboy

Reputation: 6348

How to check if button has focus?

I have a form that I am wanting to use the ENTER key to tab across the fields, but I am also wanting to submit the form when using the ENTER key when I have highlighted (by tabbing/entering to) a send button.

Is there any way in which I can tell if the enter button has been focussed?

I am thinking of something like:

<form (keydown.enter)="isSendFocussed($event)">
    <input #input1> <!-- input 1 -->
    <input #input2> <!-- input 2 -->
    <input #input3> <!-- input 3 -->
    <button #myButton (click)="sendForm()">Send</button>
</form>

I would then do something for the isSendFocussed(event) function such as:

@ViewChild('myButton') btn: ElementRef<HTMLInputElement>

isSendFocussed(event) {
    // if (!button is focussed) {
    //     block default functionality and tab across
    // } else {
    //     send form
    // }
}

Upvotes: 1

Views: 5111

Answers (2)

KShewengger
KShewengger

Reputation: 8269

You can use (focus) on your button element to check if it has been in its focused state.

Template

<button (focus)="isFocus($event)"></button>

Component

isFocus(evt): void {
  console.log('Button is focused', evt);
}

Upvotes: 1

You can use the focus and blur events like this:

<button
   (click)="onFavPopupClose()"
   (focus)="isBtnPopCloseFocused = true" 
   (blur)="isBtnPopCloseFocused = false">
</button>

Upvotes: 6

Related Questions