我的组件看起来像这样:
import { Component, OnInit } from '@angular/core';
import { Member} from '../entities/Member';
import { SearchService } from './search.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']})
export class SearchComponent implements OnInit {
members: Member[] = [];
constructor(private searchService: SearchService) { }
ngOnInit() {
this.searchService.getPartenaires().subscribe(
member=> {
this.members= member;
}
);
}
}
我还没有想出如何使用 ngFor
在 Material 表上显示我的对象。 https://material.angular.io/components/table/overview 上的示例总是使用数组作为数据源。
在将对象传递给 HTML 之前,我应该将它们放入一个数组中吗?或者有没有办法循环遍历它们?谢谢。
最佳答案
为了使用Angular Material Table
,你需要先导入MatTableModule
模块来自 import {MatTableModule} from '@angular/material/table';
到你的 app.module.ts
(如果你想使用其他功能,如 MatSort
你也必须包含它们。然后在你的 DOM 文件中你应该添加模板对于您的表格和表格列,如下所示:
<table #dataTable mat-table [dataSource]="dataSource">
<!-- COLUMN INFO -->
<!--ID Col -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef>ID</th>
<td mat-cell *matCellDef="let item"> {{item.id}} </td>
</ng-container>
<!--Name Col -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>Name</th>
<td mat-cell *matCellDef="let item">{{item.name}} </td>
</ng-container>
<!-- ROW Info-->
<tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
<tr mat-row *matRowDef="let rowData; columns: columnsToDisplay;"></tr>
</table>
在你的 component.ts
文件中,你需要做三件事:
- 定义要显示的列名称(它们应该与 DOM 文件中的
matColumnDef
匹配) - 将你的数据源引入mat表
- 在数据表上调用
renderRows()
请记住,这将自动遍历您的数据源数组并填充您不需要任何 *ngFor
的表格。只需将您的数据源保留为 Objects
的 Array
。
import { MatTableDataSource, MatTable, MatSort } from '@angular/material';
import { Component, ViewChild, OnInit }
export class DocumentListComponent implements OnInit {
@ViewChild('dataTable') dataTable: MatTable<any>;
dataSource: MatTableDataSource<ItemModel> ;
columnsToDisplay = ['id', 'name'];
ngOnInit() {
let dataSamples: ItemModel[] ;
//init your list with ItemModel Objects (can be manual or come from server etc) And put it in data source
this.dataSource = new MatTableDataSource<ItemModel>(dataSamples);
if(this.dataSource){
this.dataTable.renderRows();
}
}
}
export class ItemModel {
name: string;
id: number;
}
关于以对象作为数据源的 Angular Material 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55336045/