Как создать имя функции из json в Angular 7 - PullRequest
0 голосов
/ 03 июля 2019

Мне нужно создать динамическую кнопку из файла 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

1 Ответ

2 голосов
/ 03 июля 2019

Попробуй так:

{ 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`)
    )
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...