0

I have to create dynamic button from json file. My JSON is as per below:

{ button : { title : "Submit", event : "FunctionName", color : "white".... }}

My Component:

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

export class App {
  FunctionName:string;
  value: string;
  constructor() {
    this.FunctionName = button.FunctionName;
  }

  Button.FunctionName(){ //<-----How can I give name from JSON
    this.value = "button clicked";
  }
}

My function name is coming from JSON file. so How can I create such function in my TS file?

Enhancement of Dynamic function calling Angular 2

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
Ubiquitous Developers
  • 3,637
  • 6
  • 33
  • 78
  • Possible duplicate of [How to dynamically set a function/object name in Javascript as it is displayed in Chrome](https://stackoverflow.com/questions/5871040/how-to-dynamically-set-a-function-object-name-in-javascript-as-it-is-displayed-i) – Roberto Zvjerković Jul 03 '19 at 11:02
  • What problem are you **really** trying to solve here? This looks like a XY problem. http://xyproblem.info/ – Reactgular Jul 03 '19 at 11:47
  • Nope, it isn't XY Problem. My Question is straight forward. I want to call dynamic function named as "EVENT" in json data – Ubiquitous Developers Jul 03 '19 at 11:56

1 Answers1

2

Try like this:

{ button : { title : "Submit", event : () => this.FunctionName(), color : "white".... }}

If you cannot change the json, then this might work:

HTML:

<input type="button" value="click here" (click)="callFunction(FunctionName)">

TS:

callFunction(functionName:string) {
    let comp_obj = new ClassComponent();
    comp_obj[functionName]();
}

From stackbiltz: Add this in TS

 callFunction(FunctionName: string) {
    let x = new AppComponent();
    x[FunctionName]();
  }

  enrollmentFormProblem() {
    alert("enrollmentFormProblem called")
  }

HTML:

<button (click)="callFunction(dynamicButton[0].event)">{{this.dynamicButton[0].description}}</button>

To add the function dynamically with having it predefined, do this:

callFunction(FunctionName: string) {
    let x = new AppComponent();

    x[FunctionName] = new Function (
      console.log(`${FunctionName} created`)
    )
  }
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79