简体   繁体   English

如何在Angular 5中将组件的类方法动态分配给(单击)

[英]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.

相关问题 角度-如何通过单击按钮破坏动态零部件 - Angular - How a destroy a Dynamically component by a button click Angular 2和4-动态分配生成的组件 - Angular 2 & 4 - Assign dynamically the a generated component Angular + PIXI-如何将组件方法分配给变量并保留“ this”引用 - Angular + PIXI - How to assign a component method to a variable and preserve 'this' reference Angular为按钮动态分配操作(单击) - Angular Dynamically assign action to Button (Click) 如何在我的 Angular 应用程序中单击链接时动态添加组件 - How to dynamically add a component on link click in my Angular application 如何在画布形状单击上动态加载角度组件? - How to load an angular component dynamically on canvas shape click? Angular Typescript 为 class 属性动态赋值 - Angular Typescript assign values to class properties dynamically 如何将参数动态传递给angular 2中的click事件方法 - How to dynamically pass params into a click event method in angular 2 在 Angular 中创建一个类并在组件中使用它来赋值 - Create a class in Angular and use it in a component to assign values Angular2-如何动态创建组件并追加到主体的viewcontainer - Angular2 - How to dynamically create component and append to body's viewcontainer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM