网站搜索

angular - 触发最近的文本框被聚焦的按钮的点击事件


我在视图中有动态卡片。每张卡片上都有一个文本框,旁边有一个按钮。我想通过“回车键”触发该卡片中文本框处于焦点时按钮的点击事件。图片中显示了这些卡片。同时,我在清除所选卡片文本框内容时遇到了困难。

我尝试使用 ViewChild 清空文本框的内容

@ViewChild('bidamount') txtbidamount: ElementRef;

this.txtbidamount.nativeElement.value = '';

但是使用这种方法只有第一张卡片的文本框会被清除。

答案#1

由于你的代码生成了多个组件,你可能应该使用ViewChildren和QueryList,而不是单一的ViewChild。

所以使用这个在卡片组件中编写:

@ViewChildren('bidamount') inputBidAmount: QueryList<ElementRef>;
getClickAmount(index, item) {
    console.log(index,this.inputBidAmount.toArray()[index])
    console.log(this.inputBidAmount.toArray()[index])
}

在 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>

更新的 Stackblitz 触发最近被聚焦文本框的按钮点击事件

希望这能帮到你!!

答案#2

另外,我在清除所选卡片文本框中的内容时也遇到了困难。

既然你没有提供任何代码,这里有一些可行的代码:

  • 假设输入有某些标识符,例如 id 属性 me,以下代码会清除输入中的 before 值

document.getElementById('me').value = ''; // clear value
<input value="before" id="me"/>