加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 指定索引处的动态组件未正确放置

发布时间:2020-12-17 07:10:27 所属栏目:安全 来源:网络整理
导读:我试图在Angular中显示一个简单的项目列表,侧面有一个可点击的div;在用户选择时,组件应在单击的组件下方动态创建新组件. 为此,我使用ComponentFactoryResolver没有相关问题;但是,使用ViewContainerRef作为父级,我无法找到如何将创建的组件放在指定的索引处,
我试图在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样本来说明问题:我缺少什么或做错了什么?

澄清:

>我想在TurboTable的PrimeNg库中重现类似于“RowExpand” functionality的东西.
用户单击一行,并在单击的位置创建动态组件.
>我不知道运行时组件的类型:这就是我想要动态组件创建的原因(所以,在html模板中指定它不是我需要的)

解决方法

好的,这是@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;
  }

<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>

结果是

enter image description here

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读