【问题标题】:Angular material table not rendering dataSource rows角度材质表不呈现数据源行
【发布时间】:2019-04-11 14:05:55
【问题描述】:

我正在使用角度材料表来显示我的 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>

渲染组件:

【问题讨论】:

  • 控制台中的任何错误
  • @SachilaRanawaka 没有错误:/

标签: angular angular-material observable


【解决方案1】:

我希望你的组件有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

【讨论】:

  • 请在 stackblitz 中分享一个重现。你的组件的 ChangeDetectionStrategy 是什么?
  • 它是 ChangeDetectionStrategy.OnPush
  • stackblitz.com/edit/… 它在这里与我的更改一起工作...如果您将 changedetection 更改为 init 它将不起作用...只需尝试
【解决方案2】:

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

displayedColumns = ['id'];

Demo

【讨论】:

猜你喜欢
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 2022-10-05
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
相关资源
最近更新 更多