jeudi 7 mai 2020

Angular - How can I check a checkbox based on values in Array?

I have a form whith these checkboxes, in order to allow users to select multiple 'calibres' of an item:

Form checkbox

Those checkboxs are created through ngFor from an array called 'calibres' which have all the possible values, as shown in following code:

component.html

<div >
      <mat-checkbox #checkBox
      *ngFor="let calibre of calibres; let i = index"
      [value]="calibre"
      (change)="getCheckbox()"
      class="example-margin mb-0 mt-1" ></mat-checkbox>
</div>

getCheckbox() function on component.ts creates an array of those elements checked in my checkbox

  getCheckbox() {

    this.item.calibres = [];
    const checked = this.checkBox.filter(checkbox => checkbox.checked);
    checked.forEach(data => {
         this.item.calibres.push ( data.value );
    });
  }

When I submit the form, this array of checked elemets is stored in Backend for this particular 'item' created by the form, so the stored array will be something like [ 50,60 ]. ONLY checked checkboxes.

What Im trying to do is at the moment of filling the form ( for item 'edit' purposes ) is get checked those checkboxes stored in the array.

How can I achieve that ?




Aucun commentaire:

Enregistrer un commentaire