我有一个灵活的表格组件,它具有2种模式:
<ng-component>
标签 TableComponent
中的逻辑并不重要,模板是:
<table class="table table-hover table-sm table-middle table-crud">
<thead role="rowgroup">
<!-- SNIP -->
</thead>
<tbody *ngIf="customRowComponent" crud-table-row-renderer
[renderComponent]="customRowComponent"
[rows]="rows"
[columns]="columns"
[config]="config"
[parent]="parent"
[rowActions]="rowActions"
[cellActionEmitter]="cellActionEmitter"
[selectedRows]="selectedRows">
</tbody>
<tbody *ngIf="!customRowComponent" crud-table-row
[rows]="rows"
[columns]="columns"
[config]="config"
[parent]="parent"
[rowActions]="rowActions"
[cellActionEmitter]="cellActionEmitter"
[selectedRows]="selectedRows">
</tbody>
</table>
如您所见,一切都取决于customRowComponent
。
如果我不设置它,表格将完美工作:
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
但是,一旦我使用了一些自定义行组件,html就会变成这样:
<tbody>
<div custom-row-selector>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</div>
</tbody>
显然可以打破表。用于呈现自定义组件的组件如下所示:
@Component({
selector: '[crud-table-row-renderer]',
template: '<ng-template #container></ng-template>',
})
export class RowRenderer implements OnInit, OnChanges {
@Input() public config = new TableConfig();
@Input() public columns: FieldConfig[];
@Input() public rows: any[];
@Input() public rowActions: RowAction[];
@Input() public parent: any;
@Input() public renderComponent: any;
@Input() public selectedRows: number[];
@Input() public cellActionEmitter: any;
@ViewChild('container', {read: ViewContainerRef, static: true}) viewContainer: ViewContainerRef;
instance: TableRowComponentInterface;
constructor(
@Host() public host: ElementRef,
protected componentFactoryResolver: ComponentFactoryResolver,
) {
}
ngOnInit(): void {
this.loadRenderer();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes && changes.rows && changes.rows.currentValue) {
this.instance.rows = changes.rows.currentValue;
}
}
loadRenderer() {
const component = this.renderComponent;
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
const viewContainerRef = this.viewContainer;
const componentRef = viewContainerRef.createComponent(componentFactory);
this.instance = componentRef.instance as TableRowComponentInterface;
this.instance.config = this.config;
this.instance.columns = this.columns;
this.instance.rows = this.rows;
this.instance.rowActions = this.rowActions;
this.instance.parent = this.parent;
this.instance.selectedRows = this.selectedRows;
this.instance.cellActionEmitter = this.cellActionEmitter;
}
}
所以最大的问题是::如何确保angular不会将此动态创建的组件包装到div
或ng-component
标记中?