vendredi 30 octobre 2020

How do we set dynamic checkboxes to checked based on the value from the database in angular reactive forms?

I am new to reactive forms and struggling to set the value of the checkboxes to true dynamically. Here's an example: I am getting the pre-selected fruit values for a particular user from the db and those fruits need to be checked when the user loads the page.

I am using the below html code:

<ng-container>
<div class="form-check form-check-inline" style="display: block;" *ngFor="let control of fruitsArray.controls; let i = index;">
  <input *ngIf="i<11" class="form-check-input" [formControl]="control" type="checkbox" id="inlineCheckbox" [checked]="fruitsCheck[i].checked">
  <label *ngIf="i<11" class="form-check-label" for="inlineCheckbox"> <br /></label>
</div>

fruitsCheck is an array of object which contains the label and the checked value as below:

fruitsCheck : Array<{label: string, checked: boolean}> = [];

fruitsCheck would hold values such as:

0: {label: "Apple", checked: true},
1: {label: "Orange", checked: false},
2: {label: "Pineapple", checked: true},
3: {label: "Kiwi", checked: false}

Using the above code, I am able to just set the appropriate checboxes as checked, but however upon checking the value of the specific checkbox control, it is still shown as false.I would like the checkbox not only to be checked, but also the control's value to be set to true.

I read about patchValue but unsure of how to use it to set the value to dynamic checkboxes. Thanks in advance for any help!




Aucun commentaire:

Enregistrer un commentaire