Lux*_*001 6 typescript angular-directive angular
我试图在Angular中显示一个简单的项目列表,侧面有一个可点击的div; 在用户选择时,组件应在单击的组件下方动态创建新组件.
为此目的,我使用ComponentFactoryResolver没有相关问题; 但是,使用ViewContainerRefas parent,我无法找到如何将创建的组件放在指定的索引处,即使我将其指定为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>
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我还创建了一个stackblitz示例来说明问题:我缺少什么或做错了什么?
澄清:
好的,这是工作示例@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;
}
Run Code Online (Sandbox Code Playgroud)
和
<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>
Run Code Online (Sandbox Code Playgroud)
结果是
| 归档时间: |
|
| 查看次数: |
284 次 |
| 最近记录: |