动态渲染复杂的结构化组件



我正在尝试在我的应用程序中创建一个功能。它的工作原理就像一个拖放编辑器。我需要将一个组件放入一个确定的区域,应用程序必须动态构建该组件。对于没有子级的简单组件(例如输入(,它可以很好地使用以下代码:

const componentFactoryResolver = moduleRef.componentFactoryResolver;
const factories = Array.from(componentFactoryResolver['_factories'].keys());
const factoryClass = <Type<any>>factories.find((x: any) => x.name === component.name);
const factory = componentFactoryResolver.resolveComponentFactory(factoryClass);
const componentRef: ComponentRef<any> = factory.create(this.injector);
this.appRef.attachView(componentRef.hostView);

但是,当我必须呈现一个必须有子项的组件(如表(时,它就不起作用了。

我必须构建的结构示例:

<app-table value="dataValues">
<app-table-column prop='foo'>
<app-table-header>Foo </table-header>
</app-table-column>
<app-table-column prop='lorem'>
<app-table-header>Lorem</table-header>
</app-table-column>
</app-table>

组件应用程序表结构:

<table>
<thead>
<tr>
<th class="table-tree-header" *ngFor="let column of columns">
<ng-container *ngTemplateOutlet="column.template"></ng-container>
</th>
</tr>
</thead>
<tbody>
<app-table-row *ngFor="let row of dataSource; let i = index"
[id]="row['id']"
[row]='row'
[columns]='columns'
class="table-tree-row"
[parentId]="row['parentId']"
[isParent]="row['isParent']"
[rowIndex]='i'
[lvl]="row['lvl']">
</app-table-row>
</tbody>
</table>

应用程序表列结构:

<ng-template>
<ng-content>
</ng-content>
</ng-template>

应用程序表头结构:

<ng-content></ng-content>

应用程序表行结构:

<tr>
<td class="table-row" *ngFor="let column of columns">
{{row[column.prop]}}
</td>
</tr>

另外:当我不得不把一个独立的组件放在另一个独立组件中时,它也能工作。我的问题是,当组件相互依赖以正确渲染时。有人能帮我吗?

在我寻找解决方案的研究中,我发现当我删除列组件时,QueryList不会出现错误,因为该组件只是一个没有内容的模板。

因此,我不得不更改drop事件以直接更新QueryList:

const col = new TableColumnComponent();
col.prop = 'plataforma';
this.table.columns.reset([...this.table.columns.toArray(), col]);

我知道这不是一个完美的解决方案,但它是有效的。

最新更新