Search code examples
angularngfor

Angular - creating html elements with a function inside ngFor are not displayed correctly


I'm trying to make a reusable component in Angular 10. Here's my html

<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <div *ngFor="let element of elements">
       {{ createHtmlElement(element) }}
    </div>
</form>

and the function called is

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;
    }
}

but what i get on screen is this

[object HTMLInputElement]

is there an Angular feature that allows me to do this properly?


Solution

  • Angular has a feature which allow property binding on template.

    You can bind attributes on template like:

    <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>