动态函数调用Angular 2

时间:2017-02-08 06:43:09

标签: angular typescript dynamic-function

我在变量中有函数名,我在按钮的click事件上分配该变量。但它不起作用。任何帮助?

@Component({
  selector: 'my-app',
  template: `
    <div>
    <h2>Function name is: {{FunctionName}}</h2>
    <input type="button" value="click here" (click) = [FunctionName]()>
    </div>
    <p>{{value}}</p>
  `,
})
export class App {
  FunctionName:string;
  value: string;
  constructor() {
    this.FunctionName = 'clickFunction'
  }

  clickFunction(){
    this.value = "button clicked";
  }
}

这是代码

Plunker Code

2 个答案:

答案 0 :(得分:12)

语法必须如下:

<input type="button" value="click here" (click) ="this[FunctionName]()">

固定弹药:https://plnkr.co/edit/xGgFQuHNH72Q9FdOPEdK?p=preview

答案 1 :(得分:2)

试试这个

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Function name is: {{FunctionName}}</h2>
      <input type="button" value="click here" (click)="FunctionName()">
    </div>
    <p>{{value}}</p>
  `,
})
export class App {
  FunctionName: Fn;
  value: string;
  constructor() {
    this.FunctionName = this.clickFunction; //assign function to variable.
  }

  clickFunction(){
    this.value = "button clicked";
  }
}

在线演示:https://plnkr.co/edit/6uVZd0L0KlwMdaIKgPXq?p=preview