I'm trying to re-use my create-form to edit the values of the form. My checkbox is working as per requirement while creating a form. When I click on edit form, the values aren't patching to my checkbox. Below is my code which I have tried:
<div class="form-row">
<div class="form-group col-sm-6">
<label>Authorized To</label>
<br>
<label *ngFor="let choice of authorized; let i=index">
<input type="checkbox" [value]="choice" (change)="onCheckChange($event)" [checked]="checkedVal"
formArrayName="authorized" type="checkbox[class.invalid]="! formGrowLicense.controls['authorized'].valid && formGrowLicense.controls['authorized'].touched ">
{{choice}}
</label>
<div *ngIf="!formGrowLicense.controls['authorized'].valid && (formGrowLicense.controls['authorized'].touched || isSubmitted)">
<div class="invalid-feedback" style="display: block;">Please enter authorized to</div>
</div>
</div>
</div>
ts
authorized: any = ['CULTIVATE', 'HARVEST', 'PROCESS']; //displaying list of checkbox
constructor() {
this.formGrowLicense = this.formBuilder.group({
businessName: ['', Validators.required],
authorized: new FormArray([], [Validators.required])
});
}
getGrowLicense(id) {
this.httpService.getGrowLicenseById(id).subscribe(
response => {
this.patchGrowLicense(response);
this.checkedVal = response.authorisedTo; // tried storing response in this variable ['CULTIVATE','HARVEST']
},
(err: any) => console.log(err)
);
}
patch(licenseObj){
this.formGrowLicense.patchValue({
businessName:licenseObj.companyName,
authorized: licenseObj.authorisedTo, // here i'm getting response ['CULTIVATE','HARVEST']. Need to patch these two values as checked in checkbox
});
}
onCheckChange(event) {
this.formArray = this.formGrowLicense.get(
'authorized'
) as FormArray;
/* Selected */
if (event.target.checked) {
console.log(event.target.value);
// Add a new control in the arrayForm
this.formArray.push(new FormControl(event.target.value));
} else {
/* unselected */
// find the unselected element
let i = 0;
this.formArray.controls.forEach((ctrl: FormControl) => {
if (ctrl.value == event.target.value) {
// Remove the unselected element from the arrayForm
this.formArray.removeAt(i);
return;
}
i++;
});
}
}