javascript - 具有动态事件绑定和动态函数的 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 的方法。
解决方案
这是不可能的。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()" 时,如果条件为假,则不执行函数
推荐阅读
- python - python - 用于快速添加、删除和随机选择的数据结构
- php - 如何在静态主页的侧边栏中显示不同的内容
- r - R使用ifelse-function为多个数据框创建新列
- python - 如何使用 python 将 mp4 转换为 mp3
- javascript - 使用 Discord.js 使用 Discord Bot 将语音频道中的所有人静音
- python - 如何在 automl h2o python 中找到领导模型的最佳参数
- mysql - 为什么这个 MySQL 查询在 Live 服务器上不起作用
- docker - GitLab CI,从 docker dind 连接到 Elastic Search 服务
- angular - 在 AWS lambda 函数执行后通知客户端
- ios - 查询 Firebase 实时数据库 Swift