Angular Material - Отсутствуют определения для верхнего, нижнего колонтитула и строки; не может определить, какие столбцы следует отображать

Я получаю сообщение об ошибке при использовании компонента таблицы Angular Material. Я видел этот вопрос перед здесь, но я все еще получаю сообщение об ошибке даже после того, как сделал то, что было предложено в качестве исправления.

ОШИБКА Ошибка: отсутствуют определения для верхнего, нижнего колонтитула и строки; не может определить, какие столбцы следует отображать.

Это мой HTML-код для таблицы:

<table mat-table [dataSource]="customers" class="mat-elevation-z8">

        <!-- Position Column -->
        <ng-container matColumnDef="Name">
          <th mat-header-cell *matHeaderCellDef> Name </th>
          <td mat-cell *matCellDef="let customer"> {{ customer?.name }} </td>
        </ng-container>

        <!-- Name Column -->
        <ng-container matColumnDef="Email">
          <th mat-header-cell *matHeaderCellDef> Email </th>
          <td mat-cell *matCellDef="let customer"> {{ customer?.email }} </td>
        </ng-container>

        <!-- Weight Column -->
        <ng-container matColumnDef="Phone number">
          <th mat-header-cell *matHeaderCellDef> Phone number </th>
          <td mat-cell *matCellDef="let customer"> {{ customer?.phone.number }} </td>
        </ng-container>

        <!-- Symbol Column -->
        <ng-container matColumnDef="Notes">
          <th mat-header-cell *matHeaderCellDef> Notes </th>
          <td mat-cell *matCellDef="let customer"> {{ customer?.notes }} </td>
        </ng-container>

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

Вот мой компонентный файл TypeScript:

import { Component, OnInit } from '@angular/core';
import { Customer } from '../customers.types';
import { Router, ActivatedRoute } from '@angular/router';
import { CustomersService } from '../customers.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-customers-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss']
})
export class CustomersListComponent implements OnInit {
  customersSub: Subscription;
  detailsSub: Subscription;
  displayedColumns: string[] = [ 'Name', 'Email', 'Phone number', 'Notes' ];
  customers: Customer[] = [];
  customersLength: number;
  loadingMode: boolean = false;
  openDetailsDrawer: boolean = false;
  detailsId: string;

  constructor(private _router: Router,
              private _route: ActivatedRoute,
              public _customersService: CustomersService) { }

  ngOnInit(): void {
      this.loadingMode = true;
      this._route.queryParams.subscribe(params =>{
          this.detailsId = this._route.snapshot.params['id'];
      });

      this._customersService.getCustomers();
      this.customersSub = this._customersService.getCustomersUpdateListener()
          .subscribe((customers: Customer[]) => {
              this.loadingMode = false;
              this.customers = customers;
              this.customersLength = customers.length;
      });

      this.detailsSub = this._customersService.getDetailsUpdateListener()
          .subscribe((bool: boolean) => {
              this.openDetailsDrawer = bool;
      });
  }

  ngOnDestroy(): void {
      this.detailsSub.unsubscribe()
  }

  onOpenDetails(_id: string) {
      this._customersService.openDetails(_id);
  }

  onOpenCreate() {
      this._customersService.openCreate();
  }

}

person Bjorno    schedule 20.06.2020    source источник
comment
dev.to/jwp/angular-material-table-in- 20 минут-15f4   -  person JWP    schedule 20.06.2020


Ответы (2)


Вам нужно указать массив столбцов в вашем шаблоне, например:

файл шаблона

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

и файл контроллера

displayedColumns: string[] = ['position', 'name', 'weight', 'symbol']; 

Взгляните на все файлы в примерах: https://material.angular.io/components/table/examples

person Juan Antonio    schedule 20.06.2020
comment
Но я этим и занимаюсь. Вы не видели мой код? Я также пробовал использовать его так, как вы это делаете, без элементов таблицы HTML, и это ничего не меняет. Ошибка все еще существует. Моя реализация буквально почти такая же, как в примере на material.angular.io/components/ таблица / примеры. Единственная разница в том, какие строки отображаются. - person Bjorno; 21.06.2020

У меня все заработало, не совсем понимаю, как и почему. Я перезапустил клиент, что я делал несколько раз безуспешно. Но на этот раз все изменилось. Я не менял код. Теперь он отлично работает со статическим массивом объектов или с наблюдаемым.

person Bjorno    schedule 21.06.2020