I am trying to show a simple list of items in Angular with a clickable div on the side; on user selection, the component should dynamically create a new component below the clicked one.
For this purpose, i am using ComponentFactoryResolver
with no relevant problems; however, using ViewContainerRef
as parent, i can't find how to place the created components at a specified index, even if i specify it as a parameter in the createComponent()
method.
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;
}
}
I also created a stackblitz sample to demostrate the issue: what i am missing or doing wrong?
To clarify:
Ok, here is working example with @ViewChildren
https://stackblitz.com/edit/angular-gxmj4s?file=src%2Fapp%2Fapp.component.ts
@ViewChildren('details', { read: ViewContainerRef }) containers: QueryList<ViewContainerRef>;
thingSelected(thing: any, index: number) {
const containersArray = this.containers.toArray();
let component = containersArray[index].createComponent(this.componentFactoryResolver.resolveComponentFactory(DetailComponent));
component.instance.id = thing.id;
}
And
<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 #details></div>
</div>
</div>
Results in
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With