I'm using Angular 8 and Reactive Form.
I want to add FormArray control to the main form group.
The component is
export class RsvpComponent implements OnInit {
form: FormGroup;
constructor(
private fb: FormBuilder
) { }
ngOnInit() {
this.form = this.fb.group({
name: ['', [
Validators.required
]]
});
}
public addGuest() {
if (!this.form.get('guests')) {
this.addGuestControl();
}
this.getGuestControlArray().push(this.guestControl());
}
private addGuestControl() {
this.form.addControl('guests', new FormArray([]));
}
private getGuestControlArray() {
return this.form.get('guests') as FormArray;
}
private guestControl(): FormGroup {
const guestGroup = this.fb.group({
name: ['', [
Validators.required
]]
});
return guestGroup;
}
onSubmit() {
console.log('submitted: ', this.form.value);
}
}
The addGuest is called on click of a button. By default there will be no guests hence, no guests control in the form.
On calling the method addGuest, it first checks if guests control is there, if not then adds the control first which is a FormArray type.
This works fine on first click and controls are added, but on clicking of the submit button, onSubmit is called and the added guest data is not in the value.
When calling again addGuest the check for guests control fails.
Stackbliz: https://stackblitz.com/edit/angular-bipdyu
The weird condition: The code is working in the Stackblitz, but when I copy the same code in my component, (removing everything), it's not working.
formControlName='guests'(or [formControl]="...") is bound to a component or to a DOM element?