Angular 5:如何动态绑定列表中按钮上的事件

时间:2018-10-18 07:28:57

标签: angular5

<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>

可以说,我有一些由admin管理的工具,如果用户登录,他可以使用该工具进行编辑。

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

如果我使用ngFor将其添加到html中,则会出现类似

的错误
Got interpolation ({{}}) where expression was expected
            

2 个答案:

答案 0 :(得分:3)

如果该方法是控制器的成员,则应使用this,例如:(click)="this[tool.ToolMethod]()"

这是一个可行的示例:

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

答案 1 :(得分:2)

将大括号从(click)="{{tool.ToolMethod}}()"移到(click)="tool.ToolMethod()",然后将代码重构为类似的形式,以正确引用相应的方法:

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"
  }
];

数组和函数必须是组件的类属性。