[英]How to assign component's class method to (click) dynamically in Angular 5
I am new to angular. 我是新手。 I am using angular 5. I know you can do something like this
我正在使用角度5。我知道您可以做这样的事情
<div (click)=foo()>click me</div>
for angular to call the foo()
method in the component's class when the element is clicked. 单击元素时,Angular会在组件的类中调用
foo()
方法。 What if you want to pass methods to (click)
dynamically, that is, you don't know what will be assigned to (click)
when the view is being built like is happening below 如果您想动态地传递方法
(click)
,即不知道在构建视图时将分配给(click)
什么,该怎么办?
<ul>
<li *ngFor="let item of items" (click)=item.action>item.name</li>
</ul>
lets assume that the items array looks like this 让我们假设items数组看起来像这样
let items = [
{name: 'Smith', action: 'add'},
{name: 'Paul', action: 'delete'}
]
I want a click on the li
element containing Smith to call the add()
method and a click on the one containing Paul to call the delete()
method. 我想要单击包含Smith的
li
元素以调用add()
方法,并单击包含Paul的li
元素以调用delete()
方法。 How do I achieve this? 我该如何实现?
You can try this 你可以试试这个
let items = [
{name: 'Smith', action: () => { console.log('add');} },
{name: 'Paul', action: () => { console.log('delete');} }
]
<ul>
<li *ngFor="let item of items" (click)="item.action()">items.name</li>
</ul>
even you can have argument in your functions for example 例如,即使您可以在函数中使用参数
{name: 'Smith', action: (somearg) => { console.log('add', somearg);} },
<li *ngFor="let item of items" (click)="item.action(argvalue)">items.name</li>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.