I am new to angular 6.
I am trying to handle pushing and removing object from an array based on whether a checkbox is checked or not. So i am success to push object to array but How can I remove the same object from array when I uncheck the checkbox ? I also use formArray.
HTML Code Here
<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 Code Here
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 });
}
}
Here is a Stackblitz demo.This Example is not working properly its remove object from last.