我是5号角发展的新手.我正在try 使用这里提供的示例"https://material.angular.io/components/table/examples"开发一个带有Angular material 的数据表.

我收到一个错误,说是Can't bind to 'dataSource' since it isn't a known property of 'table'.

enter image description here

请帮忙.

推荐答案

Thanx到@Jota.托莱多,我找到了创建表格的解决方案.

component.html

<mat-table #table [dataSource]="dataSource" matSort>
  <ng-container matColumnDef="{{column.id}}" *ngFor="let column of columnNames">
    <mat-header-cell *matHeaderCellDef mat-sort-header> {{column.value}}</mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element[column.id]}}</mat-cell>
  </ng-container>

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

component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource, MatSort } from '@angular/material';
import { DataSource } from '@angular/cdk/table';

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

  dataSource;
  displayedColumns = [];
  @ViewChild(MatSort) sort: MatSort;

  /**
   * Pre-defined columns list for user table
   */
  columnNames = [{
    id: 'position',
    value: 'No.',

  }, {
    id: 'name',
    value: 'Name',
  },
    {
      id: 'weight',
      value: 'Weight',
    },
    {
      id: 'symbol',
      value: 'Symbol',
    }];

  ngOnInit() {
    this.displayedColumns = this.columnNames.map(x => x.id);
    this.createTable();
  }

  createTable() {
    let tableArr: Element[] = [{ position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
      { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
      { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
      { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
      { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
      { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
    ];
    this.dataSource = new MatTableDataSource(tableArr);
    this.dataSource.sort = this.sort;
  }
}

export interface Element {
  position: number,
  name: string,
  weight: number,
  symbol: string
}

app.module.ts

imports: [
  MatSortModule,
  MatTableModule,
],

Angular相关问答推荐

HTTP POST响应失败Angular 16

如何使用带有17角的Swiper 11.0.5元素

MAT-复选框更改事件未在onSubscriberCheck函数中返回选中的值

使用jsPDF生成带有图像的PDF时出现灰色条纹

列表和映射的SCSS语法

显示用户名-Angular

npm install命令在基本Angular 应用程序的天蓝色构建管道中失败

Angular6:RxJS switchMap 运算符未按预期工作

Angular 13 Sass 模块无法在编译中正确导入文件

BehaviorSubject 在 Angular 中制作数据之间的时间表(或计时器)

无法将项目从 Angular 13 更新到 14

如何在 cypress 测试中实现拖放?

res.json() 不是函数

如何在插值中编写条件?

Angular 5 Mat-grid 列表响应式

在 Angular 4 中播放声音

ConnectionBackend 没有提供程序

Angular - 是否有 HostListener-Events 列表?

Angular 2 组件不是任何 NgModule 的一部分

没有 ChildrenOutletContexts 的提供者 (injectionError)