Angular 使用静态数组作为mat表的数据源

Angular 使用静态数组作为mat表的数据源,angular,typescript,angular-material,Angular,Typescript,Angular Material,我正试图利用这个机会。我试图使用与示例相同的代码,但当我必须定义[dataSource]=“data”时,我遇到了一个问题 这个问题听起来可能很愚蠢,但我的表数据是一个简单的对象数组,我如何实现它 为了便于解释,假设我的数据如下所示: public data=[{ID:1,代码:“Hi”},{ID:2,代码:“Bye”}] 以下是我目前拥有的代码: <div class="example-container mat-elevation-z8"> <mat-table #

我正试图利用这个机会。我试图使用与示例相同的代码,但当我必须定义
[dataSource]=“data”
时,我遇到了一个问题

这个问题听起来可能很愚蠢,但我的表数据是一个简单的对象数组,我如何实现它

为了便于解释,假设我的数据如下所示:

public data=[{ID:1,代码:“Hi”},{ID:2,代码:“Bye”}]

以下是我目前拥有的代码:

<div class="example-container mat-elevation-z8">
    <mat-table #table [dataSource]="data">
        <ng-container matColumnDef="number">
            <mat-header-cell *matHeaderCellDef> Number </mat-header-cell>
            <mat-cell *matCellDef="let row"> {{ row.ID }} </mat-cell>
        </ng-container>

        <ng-container matColumnDef="Code">
            <mat-header-cell *matHeaderCellDef> Code </mat-header-cell>
            <mat-cell *matCellDef="let row">{{row.Code}}</mat-cell>
        </ng-container>

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

数
{{row.ID}}
代码
{{row.Code}}

即使使用静态数据,也必须实例化新的数据源

mat表始终需要@Input中的真实数据源。DataSource是一个抽象类,所以您必须实现一个从DataSource继承的类

此数据源必须实现一个方法“connect”,该方法将返回要显示的可观察数据

所以在你的情况下,类似的方法应该有效

// in your component

interface MyDataType {
    ID: number;
    Code: string;
}

export class StaticDataSource extends DataSource<MyDataType> {
  constructor(private staticData: MyDataType[]) {
    super();
  }

  connect(): Observable<MyDataType[]> {
    return Observable.of(this.staticData);
  }

  disconnect() {}
}
...
this.staticDataSource = new StaticDataSource(data);

// in your template
 <mat-table #table [dataSource]="staticDataSource">
//在您的组件中
接口MyDataType{
ID:编号;
代码:字符串;
}
导出类StaticDataSource扩展了DataSource{
构造函数(私有静态数据:MyDataType[]){
超级();
}
connect():可观察{
返回(此静态数据)的可观测值;
}
断开连接(){}
}
...
this.staticDataSource=新的staticDataSource(数据);
//在模板中
我发现这一点相当欠缺。也许我可以帮助澄清提供的例子

<mat-table [dataSource]=”dataSource”>
  ...
</mat-table>
  • matColumnDef=“userName”
    :这只是标识此ng容器的名称。注意“matColumnDef”周围缺少[],这不是绑定。它与要显示的数据无关,您可以随意命名

  • Name
    :这里没有什么进展。只需将“Name”替换为希望显示在列顶部的任何字符串

  • 放置ng容器的顺序无关紧要。事实上,在这里定义ng容器并不意味着它们将被显示。是否显示ng容器以及顺序将在以后使用
    *matHeaderRowDef
    确定

  • {{user.name}
    :在这里,您可以声明此列中显示为数据的内容。变量“user”被声明为h̲e̲r̲e̲,对您的数据没有明确的了解。您可以随意命名此变量。但是被调用的属性,即“name”,必须是绑定到数据源的数据中存在的属性

  • *matHeaderRowDef=“columnsToDisplay”
    :它负责确定将显示哪些ng容器标题。”columnsToDisplay'是一个字符串数组,包含作为标识符提供给ng容器的名称。在此数组中放置标识符的顺序决定列标题的显示顺序。如果输入ng容器的标识符,则不会显示该容器

  • 显示相应列中的行。除“columnsToDisplay”外,变量在此处声明

看起来您缺少序列化物料数据表数据的方法,该物料数据表是新的MatTableDataSource(数据)其中数据只是您的数组
<ng-container matColumnDef="userName">
  <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
  <mat-cell *matCellDef="let user"> {{user.name}} </mat-cell>
</ng-container>