问题
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