[英]How to pass values as parameters to a function call inside onclick in Angular2 without ngClick?
Angular2: I am trying to pass values from an *ngFor
loop as a parameter to function call on the (click)
attribute (since calling functions on onclick is not allowed for security reasons) event on my anchor tag. Angular2:我试图将*ngFor
循环中的值作为参数传递给我的锚标记上的(click)
属性(因为出于安全原因不允许在onclick上调用函数)事件。
Template Code: 模板代码:
<div *ngFor='let artist of artists'>
<a (click)="alert({{artist.artist_id}})" href="#">{{artist.artist_name}}</a>
</div>
Compile Time error: 编译时间错误:
Got interpolation ({{}}) where expression was expected in [alert({{artist.artist_id}})]
Problem: 问题:
How do I pass the value of artist to the function call on (click)
? 如何将艺术家的值传递给函数调用(click)
?
Any/All help appreciated! 任何/所有帮助表示赞赏! :) :)
In your case, you don't need the double-curly braces since you are passing the variable to a function in a event binding click attribute, therefore you can remove those braces and it will work as expected: 在您的情况下,您不需要双花括号,因为您将变量传递给事件绑定单击属性中的函数,因此您可以删除这些大括号,它将按预期工作:
<div *ngFor='let artist of artists'>
<a (click)="alert(artist.artist_id)" href="#">{{artist.artist_name}}</a>
</div>
According to the relevant documentation , you only need to use interpolation when inserting a value between HTML element tags and within attribute assignments (not to be confused with event/property binding). 根据相关文档 ,您只需在HTML元素标记之间和属性赋值中插入值时使用插值(不要与事件/属性绑定混淆)。
For instance, you would need to use interpolation for this direct src
attribute assignment, otherwise the value would be interpreted as a string: 例如,您需要对此直接src
属性赋值使用插值,否则该值将被解释为字符串:
<img src="{{pathUrl}}" />
However, if you were to use property binding (ie, [src]
rather than src
), it would be treated as a variable and the interpolation wouldn't be required: 但是,如果您要使用属性绑定 (即[src]
而不是src
),它将被视为变量并且不需要插值:
<img [src]="pathUrl" />
The same would apply to event binding like in your case. 这同样适用于您的情况下的事件绑定 。
In other words, as stated by Günter in the comment above , you never need to use event/property binding, (ie, ()
/ []
/ [()]
), together with variable interpolation, (ie, double-curly braces, {{}}
). 换句话说,正如Günter在上面的评论中所说 ,你永远不需要使用事件/属性绑定(即, ()
/ []
/ [()]
)和变量插值(即双花括号) , {{}}
)。
只需删除插值并调用alert(artist.artist_id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.