我有一个灵活的表格组件,有两种模式:
- 普通表 - 有效
- 自定义行模板 - 这不是因为角度添加
<ng-component>
tag
逻辑输入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
or ng-component
tag?