Angular - Undefined Material Table Reference

32 views Asked by At

I have a Component mapped to a HTML template that features a Material Table.

The component has a @ViewChild with a MatTable reference.

In the ngOnInit() method, the component does an initial retrieval of data that serves to populate the table.

A button click can activate a separate method that updates the data source for the table.

To get the view to reload, my code attempts to call this.table.renderRows().

However, table reference is undefined.

HTML template (partial):

<div [style.visibility]="dataLoading ? 'hidden' : 'visible'">
  <div class="table-div">
    <table mat-table #table [dataSource]="dataSource" matSort border="1" >

Component code:

@Component({
  selector: 'inventory-list',
  templateUrl: './inventory-list.component.html',
  styleUrls: ['./inventory-list.component.css']
})
export class InventoryListComponent implements OnInit {

  displayedColumns: string[] = ['inventoryItemId', 'manufacturerId', 'itemCondition', 'style', 'length', 'width'];
  
  dataSource: any
  dataLoading: boolean = true;

  @ViewChild(MatTable) table!: MatTable<any>;
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  public inventoryList: InventoryList

  constructor(public restApiService: RestApiService) {}

  ngOnInit() {
    this.getInventoryList();
  }

  getInventoryList() {
    this.restApiService.getInventory().subscribe(data => {
      this.inventoryList = data;
      this.loadDataToTable();
    });
  }

  getFilteredInventoryList(filterCriteria: FilterCriteria) {
    this.restApiService.filterInventoryItems(filterCriteria).subscribe(data => {
      this.inventoryList = data;
      this.loadTableUpdate();
    });
  }

  private loadDataToTable() {
    this.dataSource = new MatTableDataSource<InventoryItem>(this.inventoryList.inventoryItems);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  private loadTableUpdate() {
    this.convertTimestamps();
    this.dataSource = this.inventoryList.inventoryItems;
    this.table.renderRows();
  }

The application has a main display that shows a summary list of items in tabular form. The items are retrieved for the moment from database without any filtering and that retrieval occurs when the application first loads in browser.

A separate dialog allows user to select filters that narrow the number of items returned in the DB query. The dataSource for the table is replaced with the results of the second query.

However, the view/display does not refresh on its own. Documentation suggests it is necessary to call the table's renderRows() method to update the display.

With the help of browser's developer tools, it became clearer that the MatTable reference is undefined and the application generates an error with execution of the statement this.table.renderRows();

0

There are 0 answers