I am attempting to design a form incorporating a structure like this:
formGroup
formControl
formControl
formArray
formGroup
formControl
formControl
However, upon clicking the button to add reactive fields and submitting the form after filling it out, the first field does not retain any data. The following errors are being displayed:
ERROR Error: Cannot find control with path: 'emails -> 0 -> email'
and
ERROR Error: Cannot find control with path: 'emails -> 0 -> send'
In my app.component.ts file:
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent{
profileForm = this.fb.group({
firstName: [''],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
}),
emails: this.fb.array([''])
});
get emails() {
return this.profileForm.get('emails') as FormArray;
}
addEmail() {
this.emails.push(this.fb.group({
email:[''],
send:['']
}));
}
constructor(private fb: FormBuilder){}
public submit():void{
console.log(this.profileForm.value);
}
}
In my app.component.html file:
<form [formGroup]="profileForm" (ngSubmit)="submit()">
<div>
<label>firstName</label>
<input type="text" formControlName="firstName">
</div>
<div>
<label>lastName</label>
<input formControlName="lastName" type="text">
</div>
<div formGroupName="address">
<label>Adresse</label>
<label>street</label><input formControlName="street" type="text">
<label>city</label><input formControlName="city" type="text">
<label>state</label><input formControlName="state" type="text">
</div>
<div formArrayName="emails">
<h2>Aliases</h2>
<button type="button" (click)="addEmail()">+ Add another alias</button>
<div [formGroupName]="i" *ngFor="let e of emails.controls; let i=index;">
<div>
<label>email:</label>
<input type="text" formControlName="email">
<input type="checkbox" formControlName="send">
</div>
</div>
</div>
<button type="submit" [disabled]="!profileForm.valid">Submit</button>
</form>