h3li0s
h3li0s

Reputation: 633

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?

Upvotes: 0

Views: 2391

Answers (1)

kimy82
kimy82

Reputation: 4465

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>

Upvotes: 2

Related Questions