【发布时间】:2026-01-20 06:20:11
【问题描述】:
我试图在 Angular 中显示一个简单的项目列表,旁边有一个可点击的 div;在用户选择时,组件应在点击的组件下方动态创建一个新组件。
为此,我使用ComponentFactoryResolver 没有相关问题;但是,使用ViewContainerRef 作为父级,我无法找到如何将创建的组件放置在指定索引处,即使我在createComponent() 方法中将其指定为参数。
app.component.html
<h3>Click on the arrow to create a component below the item clicked.</h3>
<div #myContainer>
<div *ngFor="let thing of things; let index = index">
<div class="inline click" (click)="thingSelected(thing, index)"> > </div>
<div class="inline">{{thing.id}}</div>
<div class="inline">{{thing.name}}</div>
<div class="inline">{{thing.value}}</div>
</div>
</div>
app.component.ts
export class AppComponent {
@ViewChild('myContainer', { read: ViewContainerRef }) container: ViewContainerRef;
things = [];
constructor(private componentFactoryResolver: ComponentFactoryResolver){
for(let i=0; i < 10; i++)
this.things.push({id: i, name: "thing" + i, value: 5 * i});
}
thingSelected(thing: any, index: number){
let component = this.container.createComponent(this.componentFactoryResolver.resolveComponentFactory(DetailComponent), index);
component.instance.id = thing.id;
}
}
我还创建了一个stackblitz 示例来演示该问题:我遗漏了什么或做错了什么?
澄清一下:
- 我想在 PrimeNg 库的 TurboTable 中重现类似于 "RowExpand" functionality 的内容。 用户点击一行,在点击的位置创建了一个动态组件。
- 我不知道运行时组件的类型:这就是我想要创建动态组件的原因(因此,在 html 模板中指定它不是我需要的)
【问题讨论】:
-
只要您的“索引集合”是连续的,您的示例就可以工作 - 所以为了在索引 5 处放置组件,您需要已经有 5 个组件。如果您添加从 0 到 9 的所有内容,您会注意到以后的任何添加都将按您的意愿工作。 \
-
我需要将动态创建的组件插入到 NgFor 列表的“内部”,而不是在它的末尾。为了更清楚,我需要在 NgFor 的索引 N 处插入一个组件。
-
所以你真的想在 div 之间插入组件?
-
完全正确:我想重现 PrimeNg 的“RowExpand”之类的内容(请参阅我的问题中的链接)
标签: angular typescript angular-directive