简体   繁体   中英

Angular 4 Dynamically add a click event

I need to dynamically add a click event to an div tag:

<div *ngIf="item.click">
    <div (click)="item.click" >{{item.name}} (should trigger( {{item.click}})</div>
</div>

My object looks like this:

item: {name: 'Action', click: '_actionService.triggerAction()'}

I don't get any error when running the code but the click event doesn't seem to have been created.

Any suggestions?

I do not see any problem in adding a dynamic click. However, your item should be something like:

item: {name: 'Action', click: '_actionService.triggerAction'}

So, the click property in the item is the function not the result. _actionService.triggerAction() >>> _actionService.triggerAction

And then the htmlshould be something like :

<div (click)="item.click.call()" >

Hope that is helpful!

That is the actual code I have tryed:

Component:

 ... implements OnInit {

  public item: any = { name: 'name', click: () => { console.log('Some clcik has happened') } }

...

html :

<div (click)="item.click.call()"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM