如何在Angular 7中从json创建函数名称 [英] How to create function name from json in Angular 7

查看:107
本文介绍了如何在Angular 7中从json创建函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从json文件创建动态按钮.我的JSON如下所示:

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

{ 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文件中?

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

增强了调用Angular 2的动态函数

推荐答案

尝试如下:

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

如果您无法更改json,则可能会起作用:

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]();
}

在stackbiltz中:将其添加到TS

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

这篇关于如何在Angular 7中从json创建函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆