0
votes

I'm using angular material table to display my dataSource that is actually an Observable but it's not working. I tried to display it outside of the table and it's working pretty well. I also tried using changeDetectorRefs.detectChanges(). Here's my code and the rendered component.

component.ts:

ngOnInit() {
    this.getCustomers();
    this.changeDetectorRefs.detectChanges();
  }
getCustomers(): void {
  this.purchaseService.getCustomersInfo()
      .subscribe(customers => {
        this.options = customers;
        this.dataSource=customers;
      });
}
displayedColumns = ['id'];

component.html:

<div *ngFor="let element of dataSource">
  {{element.id}}
</div>
<table  mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!-- Position Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef> Customer Id </th>
    <td mat-cell *matCellDef="let element"> {{element.id}} </td>
  </ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

rendered component:

2
any errors in the consoleSachila Ranawaka
@SachilaRanawaka No errors :/TheBestAngularDeveloper

2 Answers

0
votes

I hope you component is having OnPush ChangeDetectionStrategy as below

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

Move the this.changeDetectorRefs.detectChanges(); after setting the dataSource should fix your issue.

ngOnInit() {
    this.getCustomers();
  }
getCustomers(): void {
  this.purchaseService.getCustomersInfo()
      .subscribe(customers => {
        this.options = customers;
        this.dataSource=customers;
        this.changeDetectorRefs.detectChanges();

      });
}
displayedColumns = ['id', 'name','purchases','actions'];

Working sample

0
votes

Probably because you don't setup columns for 'name','purchases','actions'. Try to remove those items from the column array

displayedColumns = ['id'];

Demo