首页 > 解决方案 > 具有动态事件绑定和动态函数的 Angular 动态表单

问题描述

嗨,我是 Angular 的新手,我需要制作一些使用 JSON 呈现表单的东西,并且 JSON 也具有所有事件和功能。这是我的 HTML 组件

    <div *ngFor="let form of forms; index as i ">
    <div *ngIf="form.type == 'input'">
        <input  type="text" value="{{ form.value }}" ("{{form.event}}") = "{{form.function}}"/>

    </div>
</div>

这是我的 TS 文件,

    @Component({
      selector: 'app-form',
      templateUrl: './form.component.html',
      styleUrls: ['./form.component.scss']
    })
    export class FormComponent implements OnInit {

      forms: any
      constructor() { }

  ngOnInit(): void {
      this.forms = [
        {
          'type' : 'input',
          'value' : '123',
          'event' : 'click',
          'function' : 'show',
        },

      ]

  }
   show(a,b){
    console.log('hello');
  }

}

我找不到使用 JSON 数组中的事件和函数生成 HTML 的方法。

标签: javascriptangularforms

解决方案


这是不可能的。Angular 转换和缩小代码,所以你不知道函数的名称

方法是你的表格是

this.forms = [
        {
          'type' : 'input',
          'value' : '123',
          'event' : 'click',
          'function' : this.show,
        },

看到“function”就是函数“this.show”

你的输入可以像

<div *ngIf="form.type == 'input'">
        <input  type="text" [ngValue]="form.value" 
          (click)="form.event=='click' && form.function($event)"
          (blur)="form.event=='blur' && form.function($event)"
          (focus)="form.event=='focus' && form.function($event)"
        />
</div>

看到当你使用 (event)="condition && function()" 时,如果条件为假,则不执行函数


推荐阅读