角材质表未渲染dataSource行

时间:2019-04-11 03:15:45

标签: angular angular-material observable

我正在使用角度材质表来显示我的dataSource,它实际上是一个Observable,但不起作用。我试图将其显示在桌子外,并且效果很好。我也尝试使用changeDetectorRefs.detectChanges()。这是我的代码和渲染的组件。

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>

渲染组件:

2 个答案:

答案 0 :(得分:0)

可能是因为您没有设置'name','purchases','actions'的列。尝试从列数组中删除这些项目

displayedColumns = ['id'];

Demo

答案 1 :(得分:0)

我希望您的组件具有如下的OnPush ChangeDetectionStrategy

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

在设置数据源后移动this.changeDetectorRefs.detectChanges();应该可以解决您的问题。

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

相关问题