Dynamic function calling Angular 2

2020-03-24 07:28发布

问题:

I have function name in a variable and I am assigning that variable on click event of button. but it is not working. Any Help?

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

Here is the code

Plunker Code

回答1:

Syntax needs to be like this:

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

Fixed plunker: https://plnkr.co/edit/xGgFQuHNH72Q9FdOPEdK?p=preview



回答2:

try this

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

Online demo: https://plnkr.co/edit/6uVZd0L0KlwMdaIKgPXq?p=preview