当我调用removeAt(I)时,它不会在指定的索引处删除。我该如何做,以消除形式数组?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>
组件
removeDriver(i: number) {
const control = <FormArray>this.driverInfoForm.controls['nameDriver'];
control.removeAt(i);
}
你不应该同时使用响应式表单和模板驱动表单。
首先从html模板中删除ngModel。
第二个依赖于FormArray控件而不是nameDriver数组值
在ts文件中定义nameDriverControl getter并使用它在html上迭代form array而不是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>
分叉的例子