When editing data, I have a form that includes checkboxes. I need to ensure that the previously selected checkboxes are checked in the edit profile form based on the array retrieved from the database.
Code snippet from app.component.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)" > {{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>
The following code captures an array of measurements from the database:
this.category = {
"_id":"5c4b0d6918f72032c0569004",
"name":"categorytest",
"measurements": [{
"measurements": [
{"name":"Chest","id":"5c4ac1c4da2dfe251aeee037"},
{"name":"Stomach","id":"5c4ac1d6da2dfe251aeee038"},
{"name":"Hip","id":"5c4ac1dbda2dfe251aeee039"},
{"name":"Length","id":"5c4ac201da2dfe251aeee03c"}
],
"label":"testfff"
},
{
"measurements":[{"name":"Chest","id":"5c4ac1c4da2dfe251aeee037"}],
"label":"httt"
}]
}
Code snippet from app.component.ts File:
this.https.post<any>('api/category/details', data).subscribe(response => {
this.category = response.category;
this.editCategoryForm.controls['name'].setValue(this.category.name);
console.log(this.category);
console.log(this.category.measurements.length);
for (let i = 0; i < this.category.measurements.length; i++) {
if (i !== 0) {
const control = <FormArray>this.editCategoryForm.controls['categoryArray'];
control.push(this.getData());
}
this.categoryArray.at(i).get('label').setValue(this.category.measurements[i].label);
}
});
Feel free to check out this StackBlitz demo.