【问题标题】:ngFor with dynamic function calls具有动态函数调用的 ngFor
【发布时间】:2019-02-23 16:45:37
【问题描述】:

我有一个名为“Action”的对象数组。每个 Action 都有 2 个参数:函数名和一个布尔值(现在不重要了)。

let  actionsArray: Action[] = [{name:"save",enabled:true},{name:"describe",enabled:true},{name:"delete",enabled:true}]

然后我使用 ngFor 来显示函数列表。我想要做的是将每个动作的“点击”事件动态绑定到它的功能。

<li *ngFor="let action of actionsArray">
        <button (click) ="this[action.name]()"> {{action.name}} </button>
</li>

我尝试了很多方法都没有成功。

【问题讨论】:

  • 是否会阻止您将函数引用直接放入元素中并执行例如(click) = "action.fn()"?
  • 为什么在html中使用this这个词?
  • @JanS 谢谢! ,我尝试过没有成功,因为我在编写函数时没有使用正确的语法。现在它正在工作。
  • @Patricio Vargas 这是我在某处找到的一个例子……我只是在尝试不同的语法
  • @Patricio Vargas 已经解决了,JanS 提议的方式对我有好处

标签: angular typescript


【解决方案1】:

我用你的代码创建了pen,它可以工作。我还添加了另一个switch/case 方法。

@Component({
  selector: 'my-app',
  template: `
    <li *ngFor="let action of actionsArray">
        <button (click) ="[action.name]()"> {{action.name}} </button>
        <button (click) ="callAction(action.name)"> {{action.name}} </button>
    </li>
  `
})
class AppComponent {  
  actionsArray: {name: string, enabled: boolean}[] = [{name:"save",enabled:true},{name:"describe",enabled:true},{name:"delete",enabled:true}]

  callAction(actionName: string) {
    switch(actionName){
      case 'save' : return this.save();
      case 'describe' : return this.describe();
      case 'delete' : return this.delete();
    }
  }

  save() {
    alert('save');
  }

  describe() {
    alert('describe');
  }

  delete() {
    alert('delete');
  }
}

【讨论】:

    猜你喜欢
    • 2018-10-20
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多