Search code examples
angulartypescriptcheckboxangular-ng-ifngmodel

Checkbox inside *ngIf panel not trigger with angular


It seems that the checkboxes inside an *ngIf condition don't trigger the event. I tried to reproduce the problem here:

https://stackblitz.com/edit/angular-7-master-uoxd3q

As you can see, we are a main component:

<div class="fake-accordion" *ngFor="let item of items; let i = index" (click)="item.expanded = !item.expanded">
  <div class="head">
    {{item.name}}
  </div>
  <app-details (click)="$event.stopPropagation(); $event.preventDefault()" *ngIf="item.expanded" [item]="item">
  </app-details>
</div>

that loops some items. Inside this loop there's another component for the details. It opens only if item.expanded is true. Inside that there are some checkboxes

<div class="details-body">
  <div>
    <input type="checkbox" [(ngModel)]="item.flag1" />Flag1
  </div>

   <div>
    <input type="checkbox" [(ngModel)]="item.flag2" />Flag2
  </div>

   <div>
    <input type="checkbox" [(ngModel)]="item.flag3" />Flag3
  </div>
</div>

but when I try to change the model it doesn't work. I tried to remove this line:

(click)="$event.stopPropagation(); $event.preventDefault()"

but in this way the detail component closes when i click somewhere inside it. Anyway, it's not working too. Is there any other way to do that?


Solution

  • Remove $event.preventDefault() from your click handler inside app-details.

    <app-details (click)="$event.stopPropagation()" *ngIf="item.expanded" [item]="item">
    </app-details>
    

    The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.