When I call removeAt(i), it doesn't remove at specified index. How should I do to remove form array? stackblitz
HTML
<form [formGroup]="driverInfoForm">
<div class="row" formArrayName="nameDriver">
<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 d-flex" [formGroupName]="i"
*ngFor="let driver of nameDriver; let i=index">
<label>{{i+1}}.Name</label>
<input class="form-control" type="text" id="name" name="name{{i}}" formControlName="name" [(ngModel)]="nameDriver[i].name"><br/>
<label>{{i+1}}.Owner Id</label>
<input class="form-control" type="text" id="ownerId" name="ownerId{{i}}" inputmode="numeric" dashFormat formControlName="ownerId" maxLength="14">
<div class="col-2 col-sm-2 col-md-2 col-lg-2 col-xl-2" >
<div class="form-group mb-0" *ngIf="i !== 0">
<button class="btn btn-danger" (click)="removeDriver(i)">
Delete
</button>
</div>
<div class="form-group mb-2">
<button *ngIf="i >= 0 && i < 1" type="button" [hidden]="nameDriver.length > 3" (click)="addDriver()" class="btn btn-primary">
Add
</button>
</div>
</div>
</div>
</div>
</form>
Component
removeDriver(i: number) {
const control = <FormArray>this.driverInfoForm.controls['nameDriver'];
control.removeAt(i);
}
You should not use reactive form and template driven form together.
First remove ngModel from html template.
Second rely on FormArray control instead of nameDriver array value
Define nameDriverControl getter inside ts file and use this to iterate form array on html instead of nameDriver
component.ts
get nameDriverControl(){
return this.driverInfoForm.get('nameDriver') as FormArray;
}
component.html
<form [formGroup]="driverInfoForm">
<div class="row" formArrayName="nameDriver">
<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 d-flex" [formGroupName]="i"
*ngFor="let driver of nameDriverControl.controls; let i=index">
<label>{{i+1}}.Name</label>
<input class="form-control" type="text" id="name" name="name{{i}}" formControlName="name" ><br/>
<label>{{i+1}}.Owner Id</label>
<input class="form-control" type="text" id="ownerId" name="ownerId{{i}}" inputmode="numeric" dashFormat formControlName="ownerId" maxLength="14">
<div class="col-2 col-sm-2 col-md-2 col-lg-2 col-xl-2">
<div class="form-group mb-0" *ngIf="i !== 0">
<button class="btn btn-danger" (click)="removeDriver(i)">
Delete
</button>
</div>
<div class="form-group mb-2">
<button *ngIf="i >= 0 && i < 1" type="button" [hidden]="nameDriver.length > 3" (click)="addDriver()" class="btn btn-primary">
Add
</button>
</div>
</div>
</div>
</div>
</form>