这些类型的组件是我最喜欢的。在一天结束的时候,如果你有这样的数据,你需要如下的东西
carData = [{
model: 'Mercedes',
year: 2015,
km: 10000
}, {
model: 'Audi',
year: 2016,
km: 5000
}];
您希望按原样显示前两列,对于最后一列,您希望显示一些自定义模板。
<app-table [data]="carData">
<app-cell header="Model" field="model"></app-cell>
<app-cell header="Year" field="year"></app-cell>
<app-cell header="Km" field="km" styleClass="km-cell">
<ng-template custom-cell-body let-car>
{{car.km | number}} km
</ng-template>
</app-cell>
</app-table>
这是你能做的。(我从角材料中得到了这个技巧,并且涂了底漆,效果很好)
你可以找到一个有效的例子
here
首先为单元格的自定义正文模板定义一个指令。(您也可以对标题执行相同的操作)
@Directive({selector: '[custom-cell-body]'})
export class AppCellBodyTemplate {
constructor(public template: TemplateRef<any>) {}
}
让我们定义一下
AppCellComponent
app-cell.component.ts
@Component({
selector: 'app-cell',
template: `<ng-content></ng-content>`
})
export class AppCellComponent {
@Input() header;
@Input() field;
@Input() styleClass;
@ContentChild(AppCellBodyTemplate) customBody: AppCellBodyTemplate;
}
让我们把它们粘在一起
AppTableComponent
app-table.component.ts
@Component({
selector: 'app-table',
templateUrl: './app-table.component.html'
})
export class AppTableComponent {
@Input() data: any[];
@ContentChildren(AppCellComponent) cells: QueryList<AppCellComponent>;
}
app-table.component.html
<table>
<thead>
<tr>
<!-- loop through cells and create header part of the table -->
<ng-container *ngFor="let cell of cells">
<th>{{cell.header}}</th>
</ng-container>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of data">
<!-- loop through cells -->
<ng-container *ngFor="let cell of cells">
<td [ngClass]="cell.styleClass">
<!-- if cell has a custom body, render that -->
<ng-container *ngIf="cell.customBody; else defaultBody">
<ng-container *ngTemplateOutlet="cell.customBody.template;
context: {$implicit: row}">
</ng-container>
</ng-container>
<!-- else render default cell body -->
<ng-template #defaultBody>{{row[cell.field]}}</ng-template>
</td>
</ng-container>
</tr>
</tbody>
</table>
这里有一些需要解释的要点。
-
template: TemplateRef<any>
在内部
AppCellBodyTemplate
因为,我们要用
custom-body-cell
具有
ng-template
一直以来,我们都可以得到在中定义的模板的引用。这个
template
将在
*ngTemplateOutlet
-
@ContentChild(AppCellBodyTemplate) customBody
在内部
应用程序单元组件
是为了检测是否存在
自定义正文单元格
定义为
ContentChild
-
@ContentChildren(AppCellComponent) cells: QueryList<AppCellComponent>
是要获取的实例
cells
(你做了类似的事)。
-
context: {$implicit: row}
是向此组件的使用者公开一些数据。
$implicit
使您能够使用所需的任何模板变量检索此上下文。自从我用过
隐式美元
在这里,我能做到
<ng-template custom-cell-body let-car>
否则,我将不得不定义
car
像这样的变量
let-car="rowData"