How to manage with Angular2 a form who hold an undefined number of field ?
In my case, I need to create a from where user can add and delete some block of fileds. It
I implemented it for you, see Plunker or better yet, Plunker -@waldo
import {Component} from 'angular2/core';
import {
FORM_DIRECTIVES, FormBuilder, ControlGroup, ControlArray, Validators, NgForm, Control,
AbstractControl
} from 'angular2/common';
@Component({
selector: 'my-app',
template: `
`,
directives: [FORM_DIRECTIVES]
})
export class AppComponent {
userForm: ControlGroup;
constructor(private fb: FormBuilder) {
this.userForm = fb.group({
name: fb.control(null, Validators.required),
firstName: fb.control(null, Validators.required),
addresses: fb.group({
address1: fb.group({
street: fb.control(null, Validators.required),
streetNumber: fb.control(null, Validators.required)
})
})
});
console.log(this.userForm);
}
objToArray(o){
return Object.keys(o);
}
addAddress() {
let addressField = this.fb.group({
street: this.fb.control(null, Validators.required),
streetNumber: this.fb.control(null, Validators.required)
});
(this.userForm.find('addresses')).addControl(
'address' + (Object.keys((this.userForm.find('addresses')).controls).length + 1), addressField);
}
}