AhammadaliPK
AhammadaliPK

Reputation: 3548

Angular 5 : how to dynamically bind events on button from a list

<div id="home" class="tab-pane fade in" style="text-align:left;opacity: 1;" >
   
  <button *ngFor="let tool of toolArray" class="m-btn btn btn-secondary" type="button" (click)="{{tool.ToolMethod}}()" placement="bottom"
      ngbTooltip="{{tool.Tooltip}}">
      <img src={{tool.ToolImgPath}} alt="" width="24" height="24"/>
  </button>

</div>

Lets say , I have some tools managed by admin , if the user logs in , he can use that tools for editing .

 let toolArray = [
    {ToolCategory: "analysis"
    ToolId: 96
    ToolImgPath: "images/zoom-selection.png"
    ToolMethod: "zoomToClickedFeature"
    ToolName: "an_zoomto_selected"
    Tooltip: "Zoom To Selected Feature"}
]

if I add this in the html using ngFor , its getting error like

Got interpolation ({{}}) where expression was expected

Upvotes: 1

Views: 214

Answers (2)

Jimmy Hedstr&#246;m
Jimmy Hedstr&#246;m

Reputation: 571

Remove the curly brackets from (click)="{{tool.ToolMethod}}()" to (click)="tool.ToolMethod()" and refactor your code to something like this, to get the reference to the corresponding method right:

public zoomToClickedFeature() {
  console.log("do something");
}

public toolArray = [
  {
    ToolCategory: "analysis",
    ToolId: 96,
    ToolImgPath: "images/zoom-selection.png",
    ToolMethod: this.zoomToClickedFeature,
    ToolName: "an_zoomto_selected",
    Tooltip: "Zoom To Selected Feature"
  }
];

Array and function must be class properties of the component.

Upvotes: 2

Andrei Tătar
Andrei Tătar

Reputation: 8295

If the method is a member of the controller, you should use this like: (click)="this[tool.ToolMethod]()".

Here's a working example:

https://stackblitz.com/edit/angular-q2l54d?file=src%2Fapp%2Fapp.component.html

Upvotes: 3

Related Questions