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?

7
  • i am not quite sure if this is possible will be glad if i am wrong Commented Sep 18, 2017 at 9: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. Commented Sep 18, 2017 at 9:22
  • I'm not sure what (click)="item.click" is supposed to do (it won't do anything how it is currently) Commented Sep 18, 2017 at 9:23
  • It's supposed to trigger the function _actionService.triggerAction() Commented Sep 18, 2017 at 9:24
  • This is not how it works, why not defining real function on item elements instead of strings ? Commented Sep 18, 2017 at 9:27

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply, but this doesn't work. I get a error: "v.parent.context.$implicit.click.call is not a function"
Is _actionService.triggerAction a function ? In that case can you post more code so we can check where is the problem
Thanks man! With your edit I was able to get this to work using " item: {name: 'Action', click: () => {this._actionService.triggerAction()} )"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.