andthereitgoes andthereitgoes - 3 years ago 217
TypeScript Question

Passing function as JSON data in angular 2 typescript

I am using angular 2.0.0 with Typescript and trying to build a dynamic menu system which works based on JSON array the component receives.

var menu = [
{id:"menu1", title: " Menu 1", action: "addUser()"},
{id:"menu2", title: " Menu 2", action: "addPhoto()"},
{id:"menu3", title: " Menu 3", action: "addEmail()"}
]


I would like to know the following


  • how to set the click action on the menu dynamically?

  • Do I use Renderer with ElementRef or do I use DynamicComponentLoader?

  • How do I represent the 'action' click function as part of the JSON array above?



Thanks for the help.

Answer Source

(click)="item.action" won't work.

You should do something like that insteard:

(click)="onClick(item)"

Then handle the logic based on item.action value inside your

     onClick(item) { 
          switch (item.action){
            case 'addUser()' :
              this.addUser()
              break;
            case 'addPhoto()' :
              this.addPhoto()
              break;
            default : whatever();
          }
     }

Or antother option is:

Change your menu to by taknig out the () from your actions:

  var menu = [
    {id:"menu1", title: " Menu 1", action: "addUser"},
    {id:"menu2", title: " Menu 2", action: "addPhoto"},
    {id:"menu3", title: " Menu 3", action: "addEmail"}
  ]

Than in your template just do: (click)="item.action ? this[item.action].call(this) : 'return false;'"

Or just: (click)="this[item.action].call(this)" incase if your item.action is compulsory

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download