首页 > 解决方案 > Angular Material:表格不包含内容

问题描述

我目前正在开发一个基于“英雄之旅”教程的小型 Angular 项目。然而,“hero/heroes”被“customer/customers”取代,但一切都是一样的编程方式。

所以我有这个模板:

<!-- This part isn't working. -->
<table #table mat-table [dataSource]="customers" class="mat-elevation-z8">

  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> ID </th>
    <td mat-cell *matCellDef="let customer"> {{customer.id}} </td>
  </ng-container>
  <ng-container matColumnDef="surname">
    <th mat-header-cell *matHeaderCellDef> Surname </th>
    <td mat-cell *matCellDef="let customer"> {{customer.surname}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
  <tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
</table>

<!-- This part works - based on Tour of Heroes -->
<h2>Customers</h2>
<ul class="customers">
  <li *ngFor="let customer of customers">
    <a routerLink="/detail/{{customer.id}}">
      <span class="badge">{{customer.id}}</span> {{customer.surname}} {{customer.lastname}}
</a>
<button class="delete" title="delete customer" (click)="delete(customer)">x</button>
  </li>
</ul>

这是模板的组件:

import { Component, OnInit } from '@angular/core';
import { Customer } from '../models/customer';
import { CustomerService } from '../customer.service';
import { MatTable } from '@angular/material';


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

  customers: Customer[];
  columnsToDisplay: ['ID', 'Surname'];

  constructor(private customerService: CustomerService) { }

  ngOnInit() {
    this.getCustomers();
  }

  getCustomers(): void {
    this.customerService.getCustomers().subscribe(customers => this.customers = customers);
  }

  delete(customer: Customer): void {
    this.customers = this.customers.filter(c => c !== customer);
    this.customerService.deleteCustomer(customer).subscribe();
  }
}

Chrome 控制台不会显示任何错误。我还在 app.module.ts 文件中导入了 MatTableModule。

我的问题与这个问题类似,但我什至没有得到头条新闻,解决方案在这里没有帮助。

如果您需要更多信息,请告诉我。

标签: angulartypescriptangular-material

解决方案


问题似乎是您对columnsToDisplay(ID, Surname) 的定义与模板中由 (position, surname) 定义的列不匹配matColumnDef,因此 Angular 无法找到/显示它们。

要么改变ts

columnsToDisplay = ['position', 'surname'];

或在HTML

<ng-container matColumnDef="ID">...</ng-container>
<ng-container matColumnDef="Surname">...</ng-container>

推荐阅读