How to create function name from json in Angular 7

一曲冷凌霜 提交于 2019-12-10 12:29:52

问题


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


回答1:


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`)
    )
  }


来源:https://stackoverflow.com/questions/56868659/how-to-create-function-name-from-json-in-angular-7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!