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

查看:25
本文介绍了如何在 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";
  }
}

<p>{{value}}</p>`,})出口类应用{函数名:字符串;值:字符串;构造函数(){this.FunctionName = button.FunctionName;}Button.FunctionName(){//<-----我如何从 JSON 中给出名称this.value = "按钮被点击";}}

<块引用>

我的函数名称来自 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天全站免登陆