Angular Material Table dataSource not binding correctly/updating, no errors yet nothing works

Issue

When inspecting served page:

<table _ngcontent-c6="" class="mat-elevation-z8 mat-table" fxfill="" 
      mat-table="" matsort="" role="grid" ng-reflect-data-source="[object Object]">

In View:

table matSort fxfill mat-table [dataSource]="dataSource" class="mat-elevation-z8"

In Controller/Constructor:

this.dataSource = new MatTableDataSource(this.section1)
this.dataSource.sort = this.sort;

this.service.getSection1().subscribe(data => {
  this.section1 = data;
  console.log(this.section1);
})

I also made a function with a button that on click, changed datasource to “BookingId”:”SomethingSomething” and when I click on it, it works.I do get intellisense errors and other stuff.

I also added console.log for dataSource in there and upon inspection, the data from the “section1” object is not being added to the dataSource.

I’ve been re-using a lot of my code from a previous project where everything works fine with this configuration.

I also have a “displayedColumns” object defined in my Controller + an interface model exported.

I’m testing this using only 1 row to make sure there’s no misspelling or other small crap that’s causing this.

Edit:

If I add this to the click function, the data is added correctly to the table even if intellisense does not like it:

this.service.getSection1().subscribe(data => {
  this.dataSource = data;
  console.log(this.section1)
})

Solution

I just added this.dataSource = new MatTableDataSource(this.section1) after the this.section1 = data; seems to have worked, now I’m just confused as to why it worked in the other app.

A couple of days later I ended up rebuilding everything with redux and used the @select() decorator on the array in my store and then subscribed to it in the constructor. This works fine as well.

Answered By – SebastianG

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.