如何在Angular material表中呈现数据源中的所有可用列?
我正试图从官方文档中生成一个有角度的材质如何在Angular material表中呈现数据源中的所有可用列?,angular,typescript,angular-material,Angular,Typescript,Angular Material,我正试图从官方文档中生成一个有角度的材质mat table 我的表大约有10列。我想知道是否可以在数据源上显示所有可用列,而不是在HTML中键入十个不同的属性?您可以使用*ngFor并显示列、标题;对于实际值,可以在TS文件中编写代码 相关的HTML: <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <ng-container *ngFor='let disCol of disp
mat table
我的表大约有10列。我想知道是否可以在数据源上显示所有可用列,而不是在HTML中键入十个不同的属性?您可以使用
*ngFor
并显示列、标题;对于实际值,可以在TS文件中编写代码
相关的HTML:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor='let disCol of displayedColumns; let i = index'>
<ng-container matColumnDef="{{disCol}}">
<th mat-header-cell *matHeaderCellDef> {{disCol}} </th>
<td mat-cell *matCellDef="let element"> {{returnVal(element, disCol)}} </td>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
import {Component} from '@angular/core';
export interface PeriodicElement {
name: string;
position: number;
weight: number;
symbol: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
{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'},
{position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
{position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
{position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
{position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];
@Component({
selector: 'table-basic-example',
styleUrls: ['table-basic-example.css'],
templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = ELEMENT_DATA;
returnVal(element, dispCol){
switch(dispCol){
case 'position': return element.position;
case 'name': return element.name;
case 'weight': return element.weight;
case 'symbol': return element.symbol;
}
}
}
完成感谢您发布解决方案。如何以不同的方式命名标题?我从数据源中获取的标题非常长,并且正在破坏整个表的呈现。如果我理解正确,您希望更改“displayedColumns”数组中的名称…是的。例如,数据源仍然有键“position”,但我想在表头中将其显示为“position\u new”。