Greg Greg - 3 years ago 239
Javascript Question

Angular dynamic form group inputs

So I have a form that has some basic family information. Then I want to have part of the form to add in children of the family. I'm using reactive forms, that looks something like this:

this.details = fb.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', Validators.compose([Validators.required, Validators.email])],
phone: ['', Validators.required]
});


Now, at some point in the UI, there will be inputs for children names, with the option to add more. Can I programatically add more input fields to the
this.details
group?

Answer Source

Sure you can. Implementation might be better, but something like this:

<button (click)="addKid()"> Add kid </button

numberOfKids: number = 0;

addKid() {
 this.numberOfKids++;
 let input = this.renderer.createElement('input');
 this.renderer.appendChild(form, input);
 this.renderer.setProperty(input, 'formControlName', this.numberOfKids); 

 this.details.addControl(this.numberOfKids, new FormControl(''));
}

So every formControl for every kid will be named as a number.

This implementation is based on Renderer2 (recommended way to "directly" manipulate DOM elements)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download