Ababababa
Ababababa

Reputation: 362

Angular material checkbox automatically un-checks itself

I have a list that I display as checkboxes using angular-material (Angular 7). Below I will add code snippet for .html and .ts files.

Whenever I click on a checkbox it is checked but then immediately un-checked. I entered in debug mode and see that when I click on a checkbox, my isSelected() method gets called 4 times by Angular. When I click on it, it immediately goes to checked state. Then it is still checked the second time that Angular calls it. On the third time, it becomes un-checked (meanwhile isSelected() is still true). I cannot figure out what I did wrong. What I tried is:

Nothing helped. What else to try, I don't know. Please help me out.

html snippet:

class MyListItem {
  id: number
  name: string
}

// omitted annotations
export class MyComponent implements OnInit, OnDestroy {
  myList: MyListItem[] = [] // omitted initialization

  isSelected(myListItem: MyListItem): boolean {
    return this.myList.includes(myListItem)
  }

  toggle(myListItem: MyListItem): void {
    // omitted the code, I debugged it and it works correctly: 
    // it adds/removes the item to/from the list
  }
}
<mat-list>
  <mat-list-item *ngFor="let myListItem of myList">
    <mat-checkbox flex="100" (click)="toggle(myListItem)" 
                  [checked]="isSelected(myListItem)">
      {{ myListItem.name }}
    </mat-checkbox>
  </mat-list-item>
</mat-list>

Upvotes: 2

Views: 1053

Answers (2)

quirimmo
quirimmo

Reputation: 9988

Use change event not click:

<mat-checkbox flex="100" (change)="toggle(myListItem)" 
                  [checked]="isSelected(myListItem)">
      {{ myListItem.name }}
    </mat-checkbox>

Upvotes: 1

Nate Gurian
Nate Gurian

Reputation: 29

I am not sure if this will work but you can add an Event parameter to the toggle function.

toggle(myListItem: MyListItem, event: any) { event.preventDefault() }

Then in your html:

(click)="toggle(myListItem, $event)"

Again, Not sure if this will work, but I have found that sometimes these click events will happen automatically, unless the prevent default() function is called

Upvotes: 1

Related Questions