如何在具有ngFor的对象数组中具有可单击的函数

时间:2019-06-02 09:23:41

标签: javascript angular typescript

我在StackBlitz Example

有一个例子

尝试在每个列表项中具有唯一的功能,然后在呈现ngFor列表后可以单击该功能。

我发现这些功能会立即启动并且无法单击。

public actions = [
    {
      label: 'Method1',
      func: this.goTo('method1')
    },
    {
      label: 'Method2',
      func: this.goTo('method2')
    },
    {
      label: 'Return method invocation',
      func: this.clickButton()
    },
  ];

   goTo(val) {
        console.log(val);
   }
   clickButton() {
        console.log('button clicked');
   }


<ng-container *ngFor="let action of actions">
  <button (click)="action.func">{{ action.label }}</button>
</ng-container>

1 个答案:

答案 0 :(得分:4)

您需要对代码进行2次更改:

  1. 在HTML文件中,更改click函数以执行func属性:
<ng-container *ngFor="let action of actions">
  <button (click)="action.func()">{{ action.label }}</button>
</ng-container>
  1. 将模型中的func属性更改为函数:
{
  label: 'Method1',
  func: () => this.goTo('method1')
}

请参阅此Forked StackBlitz project和解决方案。