Search code examples
angulartypescriptangular-materialangular-ngmodel

Get status of a dynamically generated mat-checkbox when clicking on the label


im trying to pass a dynamically generated checkbox state to a method that is called when you click the label

this is the html:

<div *ngFor="let label of consent.labels" style="flex-direction: column">
  <div [ngClass]="{'accept': consent.aceptado === true, 'optional': !consent.obligatorio }">
    <section style="margin-top: 5px;">

      <mat-checkbox color="primary" [(ngModel)]="consent.aceptado" (change)="verify()">
        <div [innerHTML]="label.label | safeHtml" (click)="detailSubConsent(checkBoxState, $event)"></div>
      </mat-checkbox>

    </section>
  </div>
</div>

as additional information, with event.preventDefault() I prevent the state of the checkbox to change when I click on the label

Is there any way to capture the current state of the dynamically generated checkbox to pass it to the method that executes on click?


Solution

  • You are always linking the same checkbox to the same ngModel, so if you have a list of them, you will end up with a lot of confusion (all of them will have the same value), you should link every separate checkbox to a different ngModel, I suggest creating a new object with keys for each label, now that I don't know your label object type definition, I will demo the solution assuming each label has a unique Id.

       <div *ngFor="let label of consent.labels" style="flex-direction: column">    
          <mat-checkbox color="primary" [(ngModel)]="obj[label.id]">
        <div [innerHTML]="label.label | safeHtml" (click)="detailSubConsent(label.id, $event)"></div>
    
          </mat-checkbox>
        </div>
    
    
       detailSubConsent(id, $event){
       //access the state as shown below 
       this.obj[id]
       }