jeudi 14 mai 2020

How to have checkboxes checked based on values are matching from two different arrays?

I am trying to check specific boxes if an array contains values of array2.

HTML

       <section class="example-section">
        <mat-label>someLabel</mat-label>
        <mat-checkbox  class="example-margin" *ngFor="let option of options let i = index" 
        #checkBox [value]="option "  name="option "  
        (change)="getCheckbox(checkBox)"></mat-checkbox>
   </section>

.ts sample

Here I am comparing two arrays to see if array1 values matches array2 values. If the array1 matches set the isCheck flag is true. else false. But seems like this logic is correct to some extent.

isChecked: boolean;

test() {
  this.user.option.forEach(user => {
    this.optionValues.forEach(element => {
        if(element == user){
          console.log("Found match @@@@" + element);
          isChecked = true;
        }else{
          console.log("No Match @@@@" + element);
          isChecked = false;                
           }
    });
  });
}

Attempt

HTML

       <section class="example-section">
        <mat-label>someLabel</mat-label>
        <mat-checkbox  class="example-margin" *ngFor="let option of options let i = index" 
        #checkBox [value]="option "  name="option " [checked]="isChecked" 
        (change)="getCheckbox(checkBox)"></mat-checkbox>
   </section>

But this will set my values as false, because it seems like it only goes to component to pull "isChecked" value after the loop is completed.

Example output

8045 @@@@@ 8069
No Match @@@@8045
8069 @@@@@ 8069
**Found match @@@@8069**
8155 @@@@@ 8069
No Match @@@@8155
8220 @@@@@ 8069
No Match @@@@8220
8299 @@@@@ 8069
No Match @@@@8299
8344 @@@@@ 8069
No Match @@@@8344
8396 @@@@@ 8069
No Match @@@@8396
8397 @@@@@ 8069

All my checkboxes will be unchecked. Based on my current logic, because the final value for "isChecked" is false. What steps or changes I need to make in order to get the HTML to check the value of isChecked during the time when it's looping with ngFor?




Aucun commentaire:

Enregistrer un commentaire