Home > Net >  Console Error in Angular- ERROR TypeError: Cannot read properties of undefined (reading 'data&#
Console Error in Angular- ERROR TypeError: Cannot read properties of undefined (reading 'data&#

Time:01-18

Full Console error:

ERROR TypeError: Cannot read properties of undefined (reading 'data")

at Oviewer Component 15A11Selected (oviewer.component.ts:97:37)

at OviewerComponent.checkbeaLabel (aviewer.component.ts:114:22)

at Oviewer Component th 26 Template (oviewer.component.html:79:68)


Oviewer.component.html


<div >

<table mat-table [dataSource]="dataSource" >

<!-- Checkbox Column --> 
<ng-container matColumnDef="select">

<th mat-header-cell *matHeaderCellDef>

<mat-checkbox

(change)="$event? toggleAllRows(): null" color="primary"

[checked]="selection.hasValue() && isAllSelected()"

[indeterminate]-"selection.hasValue() && lisAllSelected()"

[aria-label]="checkboxLabel()"

</mat-checkbox>

Oviewer.component.ts


iSAllSelected() {

const numSelected =this.selection.selected.length;

const numRows =this.dataSource.data.length;

return numSelected === numRows;

/** Selects all rows if they are not all selected; otherwise clear selection.*/

toggleAllRows() {

if (this.isAllSelected())

{

this.selection.clear();

return;

}

this.selection.select(...this.dataSource.data);

}

/** The label for the checkbox on the passed row */

checkboxLabel(row?: any): string { if (!row) { return ${this.isAllSelected() ? 'deselect' : 'select') all';

}

I am not able to found solution for this. Can someone help please why i am getting this Console error?

CodePudding user response:

You must look at the error message: it says that on the 97th line of oviewer.component.ts you try to access an objects 'data' property, but the object itself is not defined.

You did not provide the line numbers, but I suspect that that is this:

this.selection.select(...this.dataSource.data);

The datasource object is a wrapper around your data. So to use this, you must first initialize it (maybe in the class, or in the constructor with for instance dataSource = new DataSource([])) and then the Datasource will be ready for you to modify.

CodePudding user response:

It would help if you made a validation before accessing "data". Example:

const numRows = this.dataSource && this.dataSource.data ? this.dataSource.data.length : [];
  • Related