我将尝试尽可能简单地解释我的问题:
NgxDatatable
来渲染一个crud表。CrudComponent
的基本组件来处理所有的东西我现在面临的问题是为后代提供一种方式以某种方式注入自定义cellTemplate
。
我试图避免代码重复,所以我不必再次复制父模板只是为了添加1-2 ng-template
。
例如我在CrudComponent
:
@ViewChild('actionsCellRenderer') actionsCellRenderer: TemplateRef<any>;
在模板中:
<ng-template #actionsCellRenderer let-row="row" let-value="value">
<button mat-icon-button (click)="startEdit(row)">
<fa-icon [icon]="['far', 'edit']"></fa-icon>
</button>
<button mat-icon-button (click)="startDelete(row)" color="warn">
<fa-icon [icon]="['far', 'trash-alt']"></fa-icon>
</button>
</ng-template>
并且让我说我用CrudComponent
扩展这个MovieComponent
。我需要手动将整个html模板复制到新的MovieComponent.html
模板中并添加:
@ViewChild('ratingCellRenderer') ratingCellRenderer: TemplateRef<any>;
<ng-template #ratingCellRenderer let-row="row" let-value="value">
<bar-rating
[(rate)]="value"
[max]="10"
theme="horizontal"
readOnly="true"
></bar-rating>
</ng-template>
可能的解决方案:
twig
。这甚至可能吗?如果是这样,怎么样?TemplateRef<any>
表:cellRenderers = {
rating: new TemplateRef<any>(), //but how do I manually create TemplateRef?
picture: new TemplateRef<any>(),
}
然后在NgxDatatable
列中定义:
{name: 'Score', prop: 'score', cellTemplate: this.cellRenderers['rating']},
我最终删除了NgxDatatable
并编写了自己的CrudTable
实现,其中包含ColumnRendererComponent
:
import {Component, ComponentFactoryResolver, Input, OnInit, ViewChild, ViewContainerRef} from '@angular/core';
import {TableColumnType} from '../Table/TableColumnType';
import {FieldConfig} from '../../../Interface/FieldConfig';
import {RendererInterface} from './RendererInterface';
import {PlainRenderer} from './PlainRenderer';
import {FunctionRenderer} from './FunctionRenderer';
@Component({
selector: 'column-renderer',
template: `<ng-template #renderer></ng-template>`
})
export class ColumnRendererComponent implements OnInit {
@Input() public value: any;
@Input() public row: any;
@Input() public column: FieldConfig;
@Input() public columnType: TableColumnType;
constructor(
protected componentFactoryResolver: ComponentFactoryResolver,
public viewContainerRef: ViewContainerRef
) {
}
ngOnInit(): void {
this.loadRenderer();
}
loadRenderer() {
let component = this.columnType.template ? this.columnType.template :
(this.columnType.renderFn ? FunctionRenderer : PlainRenderer);
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
let viewContainerRef = this.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
let instance = <RendererInterface>componentRef.instance;
instance.column = this.column;
instance.columnType = this.columnType;
instance.row = this.row;
instance.value = this.value;
}
}