【问题标题】:Angular Return id of clicked div in ngFor loopngFor循环中单击的div的角度返回ID
【发布时间】:2018-06-24 14:46:17
【问题描述】:

我正在使用 Angular 2,并使用 *ngFor 循环创建 div。这是一般结构,经过简化:

<div *ngFor="let segment of segments ; let i = index;">
  <div></div>
    <div> 
     <button (click)="myFunction(index) )> click me </button>
    </div>
</div>

隐藏在每个 div 中的是一个按钮。我想在单击按钮时调用一个函数并传递包含 div 的索引。我该怎么做?

提前致谢。

【问题讨论】:

  • 试试&lt;button (click)="myFunction(i)"&gt; click me &lt;/button&gt;

标签: angular


【解决方案1】:
<div *ngFor="let segment of segments ; let i = index;">
  <div></div>
    <div> 
     <button (click)="myFunction(i)"> click me </button>
    </div>
</div>

【讨论】:

  • 我真的以为我试过了,内部 div 没有得到 id 引用。猜我错了。谢谢!
【解决方案2】:

正如 @TsvetanGanev 在 cmets 中建议的那样,您可以通过索引。

如果你想直接传递被点击的片段,你可以这样做:

<button (click)="myFunction(segment)"> click me </button>

如果你想要 javascript 事件:

<button (click)="myFunction($event)"> click me </button>

【讨论】:

  • 感谢您的详细回答。我将较短的设置为接受,因为它来得更快并且完成了工作。
  • @devinvail 不要忘记你也可以投票给人们的答案——在这种情况下。很高兴我能帮上忙。
  • 我很乐意,但我仍然需要提高我的声誉才能记录我的投票。这几天我会去那里的:-)
猜你喜欢
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多