【问题标题】:How to create function name from json in Angular 7如何在 Angular 7 中从 json 创建函数名
【发布时间】:2019-07-03 21:56:41
【问题描述】:

我必须从 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 文件中的函数?

Dynamic function calling Angular 2的增强

【问题讨论】:

标签: angular angular7


【解决方案1】:

试试这样:

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

【讨论】:

  • 我无法更改 JSON 文件中的值,因为它来自 API。我只能更改 Angular 代码
  • 试试这个,编辑了答案。不过我没有测试过,如果不行,请分享一个stackbiltz
  • 如果我将事件值更改为其他值而不更改enrollmentFormProblem 名称,它会起作用吗?比如 if event : "submitEvent" 会调用enrollmentFormProblem事件?
  • 无论您在事件中添加什么函数名称,该函数都必须存在于类中。就是这样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-04
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多