Home > Mobile >  Cannot read properties of undefined (reading 'checked') Angular Checkbox
Cannot read properties of undefined (reading 'checked') Angular Checkbox

Time:06-01

I need your help. I try, with the help of Angular, to check my checkbox whether it is pressed or not. If it is pressed, then I want to store the information in the database, and if not pressed, then do nothing. This code, which is shown, unfortunately gives me the following error:

Cannot read properties of undefined (reading 'checked')

What am I doing wrong? Thank you very much)

html

<mat-checkbox (change)="saveMessage($event)" formControlName="checkboxInviteMessage">
   <mat-label>Save message</mat-label>
</mat-checkbox>

ts

saveMessage(event: any) {
   if (event.target.checked) {
    console.log('added');
    // Add data to database
   } else if (!event.target.checked) {
    console.log('unchecked');
    // Don't add data to database
   }
}

CodePudding user response:

The event parameter on your saveMessage is of type MatCheckboxChange, you don't have a .target in there.

For more information, I recommend reading the Angular Material docs: link

saveMessage(event: MatCheckboxChange) {
   if (event.checked) {
    // is checked
   } else {
    //.....
   }
}
  • Related