0
votes

I want to be able to create form elements like inputs via javascript, insert it into the DOM and then add bind it to an angular reactive form.

component

var el = document.createElement('input');
document.getElementById("form").appendChild(el)
-->what to do next?

template

<form [formGroup]="form" #fromRef id="form">
    --><input>
    --><select>
</form>

EDIT

I am are of the "normal" approach to loop over "pre-binded" components or DOM elements. I am really interested if there is a way to do this completely dynamically.

1
Why do you want to bind the input like that? Can't you use reactive forms straightforwardly? toddmotto.com/angular-2-forms-reactive - Yousef khan

1 Answers

0
votes

You will have model your form in such way that you will be able to generate inputs using *ngFor directive insteed of direct DOM manipulation

check this example:

https://angular.io/guide/dynamic-form#question-form-components

It builds form dynamicly by iterating over questions. You can do the same using form array and backing model. In given example, you can change the number of questions in runtime and form will rebuild itself propertly. I think this is the closest to what you require.