Home > Enterprise >  Cannot read properties of undefined (reading 'getAttribute') mat-checkbox
Cannot read properties of undefined (reading 'getAttribute') mat-checkbox

Time:05-18

I'm trying to use some Angular Material Components such as mat-checkbox, but when I set a custom attribute, I get

Cannot read properties of undefined (reading 'getAttribute')

The code used is as it goes:

<li *ngFor="let instancia of tipo_maquina.instancias">
    <mat-checkbox 
     (change)="onCheckChange($event, $event.source, $event.checked)"
     [attr.typeid]="instancia.id">
      {{instancia.nombre}}
    </mat-checkbox>
</li>
onCheckChange(event: any, checkbox: MatCheckbox, isChecked: boolean){
    console.log("check event")
    console.log(event.target.getAttribute('typeid'));
}

CodePudding user response:

The type of $event should be MatCheckboxChange and it has 2 properties

    /** Change event object emitted by MatCheckbox. */
    export declare class MatCheckboxChange 
    {
        /** The source MatCheckbox of the event. */
        source: MatCheckbox;
        
       /** The new `checked` value of the checkbox. */
        checked: boolean;
    }

So target does not exist on MatCheckboxChange and you would get an error error TS2339: Property target' does not exist on type 'MatCheckboxChange'.

As @MikeOne suggested, just pass instancia.id to the onCheckChange($event, instancia.id) method.

  • Related