Trigger click event of button whose nearest textbox is focused
Trigger click event of button whose nearest textbox is focused
I have dynamic cards in the view. There is a text box on each card and a button next to it. I want to trigger click event of the button of that card whose text box is focused by "Enter Key". The cards shown in the picture. Also I am struggling in clearing the contents in the text box of the card selected.

I tried clearing contents of textbox using ViewChild
@ViewChild('bidamount') txtbidamount: ElementRef;
this.txtbidamount.nativeElement.value = '';
But with this approach only the textbox of the first card gets cleared.
Added card components with *ngFor
– Akshay Dusane
Aug 29 at 5:46
Is the enter key thing is doable ?
– Akshay Dusane
Aug 29 at 6:14
I have posted an answer please check below
– Sanoj_V
Aug 29 at 7:05
2 Answers
2
Since your code generates multiple components, you should probably use 'ViewChildren' and 'QueryList' rather than the singular 'ViewChild'.
So write in card component using this:
@ViewChildren('bidamount') inputBidAmount: QueryList<ElementRef>;
getClickAmount(index, item)
console.log(index,this.inputBidAmount.toArray()[index])
console.log(this.inputBidAmount.toArray()[index])
In Html:
<div *ngFor="let item of items; let i =index">
<input type="text" id="'txt'+ item.id" #bidamount/>
<button (click)="getClickAmount(i, item)">Bid</button>
</div>
UPDATED Stackblitz
Trigger click event of button whose nearest textbox is focused
Hope this help you!!
Thank you for your answer. I tried this. But its not working in my case. Actually when I am clicking button and logging this.txtbidamount.toArray() in console. I am getting all the 3 textbox whereas in fiddle that you provided only one textbox element is displayed and that's why you are able to clear the textbox
– Akshay Dusane
Aug 30 at 8:06
can you create a stackblitz where you got three textbox
– Sanoj_V
Aug 30 at 8:13
Here it is link
– Akshay Dusane
Aug 30 at 12:19
@AkshayDusane here you have pass index to that function to retrieve specific html dom??
– Sanoj_V
Aug 30 at 12:57
@AkshayDusane updated stackblitz check this
– Sanoj_V
Aug 30 at 13:07
also I am struggling in clearing the contents in the text box of the card selected.
Since you haven't provided any code here is some that will work:
id
me
before
document.getElementById('me').value = ''; // clear value
<input value="before" id="me"/>
I have now updated the code in my question
– Akshay Dusane
Aug 29 at 5:48
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Add your cards component with typescript code??
– Sanoj_V
Aug 29 at 5:32