使用ngx数据表列的角度分量



我在应用程序中经常使用ngx数据表,我希望为列及其各自的标题提供一些通用模板。

现在我有

<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数据表中搜索避免复制的更好方法浪费了大量时间。这是我的解决方案:

  1. 创建新的组件处理程序,我称之为-">自定义表">
  2. 向该组件提供行和列@输入
  3. 侦听更改列并重写列属性
  4. 使用自定义表单元格声明ViewChild

自定义表格.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],
}));
}
}

customitable.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>

之后你可以这样使用它。

示例组件.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>

示例组件表.config.ts

export const ExampleListColumns: TableColumnModelExtended[] = [
{
cellTemplate: 'primary',
name: 'Quantity',
prop: 'quantity',
cellClass: 'right',
},
{
cellTemplate: 'withAvatar',
name: 'Avatar',
prop: 'userAvatar',
}
];

定义列配置时要小心。您应该而不是在数组结束后使用额外的","。

最后,您会得到一个表,该表使用config来显示组件,并且不会重复html代码

要添加新列类型,只需在组件内对其进行一次描述,并在组件内创建@ViewChild

最新更新