0

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?

h3li0s
  • 613
  • 9
  • 25
  • i am not quite sure if this is possible will be glad if i am wrong – Rahul Singh Sep 18 '17 at 09:21
  • 2
    There is no way to add click handlers dynamically using Angular bindings. Rather do something like `(click)="item.click ? doSomething($event) : null"` to only call `doSomething()` in case of a user click when `item.click` is truthy. – Günter Zöchbauer Sep 18 '17 at 09:22
  • I'm not sure what `(click)="item.click"` is supposed to do (it won't do anything how it is currently) – Günter Zöchbauer Sep 18 '17 at 09:23
  • It's supposed to trigger the function _actionService.triggerAction() – h3li0s Sep 18 '17 at 09:24
  • This is not how it works, why not defining real function on `item` elements instead of strings ? – n00dl3 Sep 18 '17 at 09:27
  • I need this because the actions will be dynamic. This is possible with pure typescript, but I would like to do this in the template if possible – h3li0s Sep 18 '17 at 09:29
  • something like https://stackoverflow.com/questions/42966681/adding-a-click-event-to-a-dynamically-created-html-element-using-angular2 ? or https://stackoverflow.com/questions/35080387/dynamically-add-event-listener-in-angular-2? – eko Sep 18 '17 at 10:14

1 Answers1

2

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>
kimy82
  • 4,069
  • 1
  • 22
  • 25
  • Thanks for the reply, but this doesn't work. I get a error: "v.parent.context.$implicit.click.call is not a function" – h3li0s Sep 18 '17 at 09:56
  • Is **_actionService.triggerAction** a function ? In that case can you post more code so we can check where is the problem – kimy82 Sep 18 '17 at 09:59
  • Thanks man! With your edit I was able to get this to work using " item: {name: 'Action', click: () => {this._actionService.triggerAction()} )" – h3li0s Sep 18 '17 at 10:20