angular - 如何在 Angular 7 中从 json 创建函数名称
问题描述
我必须从 json 文件创建动态按钮。我的 JSON 如下:
{ button : { title : "Submit", event : "FunctionName", color : "white".... }}
我的组件:
@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";
}
}
我的函数名称来自 JSON 文件。那么如何在我的 TS 文件中创建这样的功能呢?
解决方案
试试这样:
{ button : { title : "Submit", event : () => this.FunctionName(), color : "white".... }}
如果您无法更改 json,那么这可能会起作用:
HTML:
<input type="button" value="click here" (click)="callFunction(FunctionName)">
TS:
callFunction(functionName:string) {
let comp_obj = new ClassComponent();
comp_obj[functionName]();
}
来自 stackbiltz:在 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>
要在预定义的情况下动态添加函数,请执行以下操作:
callFunction(FunctionName: string) {
let x = new AppComponent();
x[FunctionName] = new Function (
console.log(`${FunctionName} created`)
)
}
推荐阅读
- django - Django Rest Framework 可选地覆盖视图集列表方法?
- java - ActiveMQ 多次处理消息
- python - 有什么方法可以区分这两个功能吗?
- laravel - 使用 laravel 上传图片并在数据库中存储 url
- ios - 用图像替换一组相似颜色的像素 - iOS
- android - 在 android 8.1.0 上安装 burp 证书后出现“您的连接不是私人的”错误
- c# - 为什么没有触发异步套接字 send.completed 事件?
- python - SQL 注册表单
- makefile - 在 GNU Make 3.81 中保留先决条件的尾部斜杠
- wallet - Apple Pass类型证书的注册