我在我的应用程序中使用了很多ngx-datable,我想为列和它们各自的标题提供一些通用模板。
现在我有
<ngx-datatable #myTable
XXX>
<ngx-datatable-column
name="selection">
<ng-template let-column="column" ngx-datatable-header-template>
<app-component-header-table></app-component-header-table>
</ng-template>
<ng-template let-row="row" ngx-datatable-cell-template>
<app-component-content-table></app-component-header-table>
</ng-template>
</ngx-datatable-column>
.... rest of the table ...
</ngx-datatable>
我想实现的是将包含内容的组件和包含标题的组件放在一个单独的文件组件中。
并且使用它或多或少是这样的。
<ngx-datatable #myTable
XXX>
<ngx-datatable-column
name="selection">
<app-custom-column></app-custom-column>
</ngx-datatable-column>
.... rest of the table ...
</ngx-datatable>
显然,可以在里面访问对象的列和行。
在寻找更好的方法来避免ngx-datable中的复制时,浪费了很多时间。
自定义表格.ts
export class CustomTableComponent implements OnInit, OnChanges {
columns = [];
@ViewChild('table', { static: false }) table: any;
@ViewChild('primary', { static: true }) primary: TemplateRef<any>;
@ViewChild('withAvatar', { static: true }) withAvatar: TemplateRef<any>;
@Input() rows: Array<any>;
@Input() cols: Array<Object>;
public selected: TableColumnModelExtended[] = [];
ngOnChanges(changes: SimpleChanges): void {
if (changes.hasOwnProperty('cols') && changes.cols.currentValue) {
this.updateCols();
}
}
ngOnInit() {
if (this.cols) {
this.updateCols();
}
}
updateCols(): void {
this.columns = this.cols.map((col: TableColumnModelExtended) => ({
...col,
cellTemplate: this[col.cellTemplate],
headerTemplate: this[col.headerTemplate],
}));
}
}
自定义表格.html
<div class="custom-table">
<ngx-datatable
#table
columnMode="force"
[rows]="rows"
[columns]="columns">
</ngx-datatable>
<!--COLUMN WITH AVATAR-->
<ng-template #withAvatar let-value="value" let-row="row">
<column-with-avatar [value]="value"></column-with-avatar>
</ng-template>
<!--PRIMARY COLUMN-->
<ng-template #primary let-value="value" let-row="row" let-column="column">
<column-primary [value]="value" [column]="column"></column-primary>
</ng-template>
</div>
之后你就可以像这样使用它。
example-component.ts
export class ExampleComponent {
public columns: TableColumnModel[] = ExampleListColumns;
readonly valueList$: BehaviorSubject<DeliveryNote[]> = new BehaviorSubject([]);
}
example-component.html
<custom-table
[rows]="valueList$ | async"
[cols]="columns">
</custom-table>
example-component-table.config.ts)。
export const ExampleListColumns: TableColumnModelExtended[] = [
{
cellTemplate: 'primary',
name: 'Quantity',
prop: 'quantity',
cellClass: 'right',
},
{
cellTemplate: 'withAvatar',
name: 'Avatar',
prop: 'userAvatar',
}
];
在定义列配置时要小心。你应该 不 在数组结束后使用额外的','。
在最后,你会得到一个 表,使用配置 来显示组件,以及 不重复html代码 一遍又一遍。
要添加一个 新栏目 类型,你只需要在组件中描述一次,然后创建一个 组件内的@ViewChild.