【问题标题】:Trigger click event of button whose nearest textbox is focused触发最近文本框聚焦的按钮的单击事件
【发布时间】:2018-08-30 21:06:21
【问题描述】:

我的视图中有动态卡片。每张卡片上都有一个文本框,旁边有一个按钮。我想触发其文本框以“输入键”为焦点的卡片按钮的单击事件。如图所示的卡片。我也在努力清除所选卡片文本框中的内容。

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

@ViewChild('bidamount') txtbidamount: ElementRef;

this.txtbidamount.nativeElement.value = '';

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

【问题讨论】:

  • 用打字稿代码添加你的 cards 组件??
  • 使用 *ngFor 添加卡片组件
  • 回车键可行吗?
  • 我已经发布了答案,请查看下方

标签: angular typescript


【解决方案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 Trigger click event of button whose nearest textbox is focused

希望对你有帮助!!

【讨论】:

  • 感谢您的回答。我试过这个。但它不适用于我的情况。实际上,当我单击按钮并在控制台中记录 this.txtbidamount.toArray() 时。我得到了所有 3 个文本框,而在小提琴中,您只提供了一个文本框元素显示,这就是您能够清除文本框的原因
  • 你能在有三个文本框的地方创建一个 stackblitz
  • @AkshayDusane 在这里您已将索引传递给该函数以检索特定的 html dom??
  • 非常感谢。这是一个很好的解决方法。但是现在我想触发其文本框以“Enter Key”为焦点的卡片按钮的点击事件。
【解决方案2】:

我也在努力清除所选卡片文本框中的内容。

由于您没有提供任何代码,这里有一些可以工作:

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

document.getElementById('me').value = ''; // clear value
&lt;input value="before" id="me"/&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多