【发布时间】:2019-02-06 13:52:44
【问题描述】:
我是 Angular 6 的新手。
我正在尝试根据是否选中复选框来处理从数组中推送和删除对象。 所以我成功地将对象推送到数组但是当我取消选中复选框时如何从数组中删除相同的对象? 我也使用 formArray。
此处为 HTML 代码
<form [formGroup]="editCategoryForm" >
<div class="form-group">
<mat-form-field>
<input matInput placeholder="Name" formControlName="name" >
</mat-form-field>
</div>
<div formArrayName="categoryArray" >
<fieldset *ngFor="let address of editCategoryForm.controls.categoryArray['controls']; let i = index" >
<div [formGroupName]="i" >
<div class="form-group">
<mat-form-field>
<input matInput placeholder="Label" formControlName ="label" required>
</mat-form-field>
<br/>
<div class="check-box" *ngFor="let data of measurementData">
<input type="checkbox" (change)="onChange(i,data._id,data.name, $event.target.checked)" [checked]="inputChecked(i,data)" > {{data.name}}
</div>
<div class="col-sm-1">
<button mat-mini-fab color="warn" *ngIf="editCategoryForm.controls.categoryArray['controls'].length > 1" title="Remove Fields" (click)="removeLair(i)">x</button>
</div>
</div>
</div>
</fieldset>
<br/>
<div class="form-group">
<button mat-raised-button color="accent" (click)="addNew()">Add Measurement</button>
</div>
<div class="form-group">
<button style="float: right;margin: 29px;" mat-raised-button color="primary" (click)="submitdata()">Submit</button>
</div>
</div>
</form>
这里是 TS 代码
onChange(index: number, _id: string, name: string, isChecked: boolean) {
if (isChecked) {
this.editCategoryForm.controls.categoryArray.value[index].measurements.push({ id: _id, name: name });
} else {
this.editCategoryForm.controls.categoryArray.value[index].measurements.pop({ id: _id, name: name });
}
}
这是一个Stackblitz demo。此示例无法正常工作,它从最后一个删除对象。
【问题讨论】: