Hey there, Alex! Looks like you have a Form Array of FormControls instead of a Form Array of formGroups. To reflect this in your .html file...
<form *ngIf="addForm" [formGroup]="addForm">
<div class="form-control-row" formArrayName="email"
*ngFor="let item of addForm.get('email').controls; let i = index;">
<div class="input-box">
<input type="text" placeholder="E - mail" [formControlName]="i">
<img src="../../assets/Delete.svg" alt="x-icon">
</div>
</div>
</form>
Notice that you should use [formControlName]="i" instead of [fomGroupName]="i". Another way to approach this is by using...
<form *ngIf="addForm" [formGroup]="addForm">
<div class="form-control-row" formArrayName="email"
*ngFor="let item of addForm.get('email').controls; let i = index;">
<div class="input-box">
<input type="text" placeholder="E - mail" [formControl]="item">
<img src="../../assets/Delete.svg" alt="x-icon">
</div>
</div>
</form>
In this case, we utilize [formControl]="item" within the loop. How did you create the formArray?
If you have an array of emails, you can do something like this:
email: this.formBuilder.array(
this.email.map(x=>this.formBuilder.control(x))
)
This creates an array of FormControls using map function. Remember, in production, you need a getter for the array...
get emails()
{
return this.form.get('email') as FormArray;
}
And then iterate over it using...
*ngFor="let item of emails.controls; let i = index;">
The usage of [formGroupName]="i" and formControl typically applies to a FormArray of FormGroups. For example...
email: this.formBuilder.array(
this.email.map(x=>this.formBuilder.group({email:x}))
)
By transforming each element into a FormGroup with a FormControl "email". Check out this example on StackBlitz for a better understanding.
To add an element to the formArray, you can create a function like so:
addEmail(email:any)
{
const array=this.addForm.get('email') as FormArray
array.push(this.formBuilder.control(email))
const array2=this.addForm.get('email2') as FormArray
array2.push(this.formBuilder.group({email:email}))
}
Note: To initialize an empty formArray initially, you should use...
email: this.formBuilder.array([])
When removing an element from the array, remember to pass the proper index to the delete function like so:
delete(index:number)
{
const array=this.addForm.get('email') as FormArray
array.removeAt(index)
}
Update your .html code accordingly with a click event for deletion:
<div class="input-box">
<input type="text" placeholder="E - mail" [formControl]="item">
<img src="../../assets/Delete.svg" alt="x-icon" (click)="delete(i)">
</div>