首页 > 解决方案 > 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 功能?

标签: angularngfor

解决方案


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>

推荐阅读