7

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

2 Answers 2

20

Syntax needs to be like this:

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

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

Sign up to request clarification or add additional context in comments.

8 Comments

Is it possible if I do the same with child-parent related component. Like I write (click) = "this....." on child components selector. and define the function on parent component's ts file. will it work?
@amansoni211 but the child components template scope will be out of the parents scope. I don't think that will work.
Will this work if I define this function in parent component? call it in childs template like we are doing above.
@amansoni211 isn't it the same thing with your previous comment? Create a new question about it maybe with a clear usage?
What if the event name is also dynamic and coming from json variable. how I can make this dynamic clickFunction(){ this.value = "button clicked"; } my function name is coming from json file
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.