单击行后插入动态创建组件

Insert dynamically create component after clicked row

我正在研究解决方案,我想在单击行后附加动态创建的组件

我有 table 包含带有操作按钮的行,单击该按钮我将调用 angular 函数并在该行之后加载组件。

这是table代码

<div class="row" *ngFor="let rData of reportData; let i = index;" >
        <div class="col" >
            <button class="btn btn-sm" (click)="loadChildComponent()">+</button>
        </div>
        <div class="col">Name</div>
        <div class="col">Description</div>
        <ng-template #dynamic></ng-template>

</div>

动态组件代码

Service.ts


import { DynamicComponent } from './dynamic.component'
@Injectable()
export class Service {
  factoryResolver;
  rootViewContainer; 
  constructor(@Inject(ComponentFactoryResolver) factoryResolver) {
    this.factoryResolver = factoryResolver
  }
  setRootViewContainerRef(viewContainerRef) {
    this.rootViewContainer = viewContainerRef
  }
  addDynamicComponent() {
    const factory = this.factoryResolver
                        .resolveComponentFactory(DynamicComponent)

    const component = factory
      .create(this.rootViewContainer.parentInjector)

    this.rootViewContainer.insert(component.hostView)
  }
}

这里是组件文件。

dynamic.component.ts

import { Component } from '@angular/core'
@Component({
  selector: 'dynamic-component',
  template: `<div class="row"  >
            <div class="col">Data</div>
            <div class="col">Data</div>
            <div class="col">Data</div>
            <div class="col">Data</div>
            <div class="col">Data</div>
            <div class="col">Data</div>
            <div class="col">Data</div>
    <ng-template #dynamic></ng-template>
    </div>`
})
export class DynamicComponent { }

用于呈现动态组件的函数

@ViewChild('dynamic', { 
      read: ViewContainerRef 
    }) viewContainerRef: ViewContainerRef

loadChildComponent() {
        this.service.setRootViewContainerRef(this.viewContainerRef)
        this.service.addDynamicComponent()
    }

现在它在相同的 div 中附加任何行

我想在点击行后追加它

请帮忙..

Angular 中的 ng-template 就像一个幽灵元素,即它永远不会直接显示。检查这个 link.

更新:

您总是在第一行插入模板,因为您使用了 @ViewChild。 @ViewChild 查找模板中的第一个元素。

请尝试使用 @ViewChildren

参考以下改动:

<ng-container *ngFor="let rData of reportData; let i = index;">
    <div class="row">
        <div class="col" >
            <button class="btn btn-sm" (click)="loadChildComponent(i)">+</button>
        </div>
        <div class="col">Name</div>
        <div class="col">Description</div>

    </div>
    <div class="row">
        <ng-template #dynamic></ng-template>
    </div>
</ng-container>

JS 变化:

@ViewChildren('dynamic', { read: ViewContainerRef }) viewContainerRef: QueryList<ViewContainerRef>

loadChildComponent(index) {
        this.service.setRootViewContainerRef(this.viewContainerRef.toArray()[index])
        this.service.addDynamicComponent()
    }

希望这对您有所帮助:)