angular - Angular - 在 ngFor 中使用函数创建 html 元素无法正确显示
问题描述
我正在尝试在 Angular 10 中制作一个可重用的组件。这是我的 html
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div *ngFor="let element of elements">
{{ createHtmlElement(element) }}
</div>
</form>
调用的函数是
createHtmlElement(element): HTMLElement {
if (element.input) {
const input = document.createElement("input")
input.type = element.type;
input.id = element.id;
input.className = 'form-control';
input['formControlName'] = element.id;
return input;
}
}
但我在屏幕上看到的是这个
[object HTMLInputElement]
是否有允许我正确执行此操作的 Angular 功能?
解决方案
Angular 具有允许在模板上绑定属性的功能。
您可以在模板上绑定属性,例如:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div *ngFor="let element of elements">
<input [type]="element.type" [id]="element.id" class="form-control" [formControlName]="element.id" />
</div>
推荐阅读
- python - 如何附加多个 CSV 文件并在 Python 中添加指示文件名的附加列?
- c# - Web 浏览器 等待按钮加载
- c# - 如何保存和加载用户创建的游戏对象?
- javascript - 调用类和扩展类中的方法,并使用 if else 传递参数
- google-chrome - TypeError:无法读取未定义的属性“同步”。我该如何解决这个问题?
- python - Django 编辑表单安全方式
- bash - 将txt转换为分栏文件
- reactjs - 类型“{}”不可分配给类型“ComponentProps”
- wordpress - 在 WordPress 中的特定帖子标题上添加当前时间
- html - 我如何正确对齐图像?