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

3

1 Answer 1

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`)
    )
  }
Sign up to request clarification or add additional context in comments.

5 Comments

I can not change value in JSON file, as it is coming from API. I can only Change in Angular code
Try this, Editted the answer. I haven't tested it though, if it doesn't work, please share a stackbiltz
will it work if I change event value to some other value without changing enrollmentFormProblem name? like if event : "submitEvent", it will call enrollmentFormProblem event?
Whatever function name you add in the event, that function has to be present in the class. That's all

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.