I have created a card component in Angular:
<div (keyup.enter)="onUploadButtonClick()">
<div >
<img src="path-to-image"/>
</div>
<div >
<form [formGroup]="myFormGroup">
<label>First Input:</label>
<input type="text" formControlName="input1">
...
</form>
</div>
</div>
Now, I would like to achieve the following: Whenever I have clicked into the card, upon hitting the Enter key, I want to call onUploadButtonClick()
. It is partly working correctly already: When the focus is on one of my input fields, upon hitting the Enter key, the onUploadButtonClick()
method is called. However, it seems that the keyup event can only be fired from within an input field. I would like to fire this event as well when I have previously clicked onto my card, but my current focus is not on an input field. Is there a way to achieve this? Also: What I don't want is to fire this event whenever I hit Enter anywhere inside my application, only when I have previously clicked onto the card.
CodePudding user response:
I'm not 100% clear on the question, but it seems you want keyup
events to trigger from non input
elements in the component
You'll need to make those elements focusable to register keyboard events. Try adding tabindex="0"
to the div(s)
CodePudding user response:
Sounds like you should save the information whether the user has previously clicked on the card:
add a flag for that information into your controller:
public userHasClicked = false;
add logic to switch userHasClicked to true when the user clicks on the card:
<div (keyup.enter)="onUploadButtonClick()" (click)="userHasClicked=true">
...
</div>
add a check for that flag before executing the code insude onUploadButtonClick()
:
before:
onUploadButtonClick() {
// your code
}
after:
onUploadButtonClick() {
if (this.userHasClicked) {
// your code
}
}
CodePudding user response:
It's possible to listen the keyup event globally in your component by using @Hostlistener. Check this https://angular.io/api/core/HostListener#description
You will need a property in your component to save the last div clicked, base on that you could invoke onUploadButtonClick() or not