我更改了 mat-table 中的方向列,之后我无法将 ng-container 添加到表中。我做的像this .在这种情况下如何使用我的内容添加预定义行?
component.ts
export class MyComponent implements OnInit {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol', 'actions'];
dataSource = ELEMENT_DATA;
fourthFormGroup: FormGroup;
displayColumns: string[];
displayData: any[];
constructor(
private _formBuilder: FormBuilder
) { }
ngOnInit() {
this.displayColumns = ['0'].concat(this.dataSource.map(x => x.position.toString()));
this.displayData = this.displayedColumns.map(x => this.formatInputRow(x));
this.fourthFormGroup = this._formBuilder.group({});
}
formatInputRow(row) {
const output = {};
output[0] = row;
for (let i = 0; i < this.dataSource.length; ++i) {
output[this.dataSource[i].position] = this.dataSource[i][row];
}
return output;
}
}
component.html
<table mat-table [dataSource]="displayData" class="mat-elevation-z8">
<!-- Position Column -->
<ng-container [matColumnDef]="column" *ngFor="let column of displayColumns">
<th mat-header-cell *matHeaderCellDef> {{ column }} </th>
<td mat-cell *matCellDef="let element"> {{ element[column] }} </td>
</ng-container>
<!-- Below Colunm doesn't show -->
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Actions </th>
<td mat-cell *matCellDef="let element">
<button (click)="accept($event)">Accept</button>
<button (click)="remove($event)">Remove</button>
</td>
</ng-container>
<tr mat-row *matRowDef="let row; columns: displayColumns"></tr>
</table>
最佳答案
添加一个 ng-container
将添加一个新的 matColumnDef
。您不需要列,而是需要显示新行。
因为您只是将 displayColumns
映射为新的“水平”表标题。您只需在此处添加 actions
即可查看新行。
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol', 'actions'];
现在要显示您的静态内容,我们需要修改您的模板。我们知道 element[0]
中存在“水平”表头,我们可以将其与 *ngIf
一起使用以正确显示新行。
<ng-container [matColumnDef]="column" *ngFor="let column of displayColumns">
<th mat-header-cell *matHeaderCellDef> {{ column }} </th>
<td mat-cell *matCellDef="let element">
<span *ngIf="column == 0 || element[0] !== 'actions'; else actions">{{ element[column] }}</span>
<ng-template #actions>
<button (click)="accept($event)">Accept</button>
<button (click)="remove($event)">Remove</button>
</ng-template>
</td>
</ng-container>
这是关于 StackBlitz 的工作示例.
关于angular - 如何将静态内容添加到我的水平 Angular 垫表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57471900/