首页 > 解决方案 > 如何在 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 文件中创建这样的功能呢?

增强动态函数调用 Angular 2

标签: angularangular7

解决方案


试试这样:

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

推荐阅读