Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MatTableDataSource : cannot read property 'length' of undefined

Im getting following error while using angular material data table. i am able to get the data from api but cannot render it in view.

Error:

error Image

TS:

      dataSource = new MatTableDataSource();  
      displayedColumns: string[] = ["Part#", "Description"];      
      getSearchResult() {
         let params = {
             ParentCategoryID: 0,
             CategoryID: 0,
             ManufacturerID: 0,  
       };
        this._httpService.getSearchResult(params).subscribe((resp: any) => {
        this.searchResult = resp;
        this.dataSource.data = this.searchResult;                 
       });
    }

View:

    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> 
        <ng-container matColumnDef="Part#">
           <th mat-header-cell *matHeaderCellDef> Part# </th>
           <td mat-cell *matCellDef="let element "> {{element.PartCode}}            
          </td>
        </ng-container>

        <ng-container matColumnDef="Description">
          <th mat-header-cell *matHeaderCellDef> Description </th>
          <td mat-cell *matCellDef="let element "> 
              {{element.DiagramDescription}} </td>
         </ng-container>    

        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      </table>
like image 746
Asridh Kumar Avatar asked Sep 25 '18 09:09

Asridh Kumar


3 Answers

Try putting dataSource = new MatTableDataSource(); inside the Constructor:

constructor() {
    dataSource = new MatTableDataSource();
}
like image 100
A-Sharabiani Avatar answered Nov 11 '22 04:11

A-Sharabiani


make initialisation inside constructor

this.dataSource.data = [];

OR

add the subscribe code inside constructor

constructor(private _httpService: imported service name) {this._httpService.getSearchResult(params).subscribe((resp: any) => {
    this.searchResult = resp;
    this.dataSource.data = this.searchResult;                 
   });}
like image 41
Srinivasan N Avatar answered Nov 11 '22 04:11

Srinivasan N


Please try this code:

this.dataSource= new MatTableDataSource(this.searchResult);

like image 2
Amol B Lande Avatar answered Nov 11 '22 06:11

Amol B Lande